Android 以整数和浮点形式显示复数

标签 android

我的目标是显示“1 星”“2.5 星”“3 星”等文本。

对于 1.0、2.0 等浮点值,删除 .0 但对于 .5 的值显示浮点值 2.5 3.5 等

这可以使用 android plurals 吗?

我用过这个方法,但是不行。 plurals.xml

<plurals name="hotel_card_rating_text">
        <item quantity="zero">@string/text_zero</item>
        <item quantity="one">@string/text_one</item>
        <item quantity="two">@string/text_two</item>
        <item quantity="few">@string/text_few</item>
        <item quantity="many">@string/text_many</item>
        <item quantity="other">@string/text_other</item>
    </plurals>

strings.xml

<resources>
    <string name="text_zero">%.1f stars</string>
    <string name="text_one">1 star</string>
    <string name="text_two">%.1f stars</string>
    <string name="text_few">%.1f stars</string>
    <string name="text_many">%.1f stars</string>
    <string name="text_other">%.1f stars</string>
</resources>

测试代码

 DecimalFormat format = new DecimalFormat();                    
    float rating = getRating();
    getStarText().setText(getContext().getResources().getQuantityString(R.plurals.hotel_card_rating_text, (int) rating, format.format(rating)));
            }

最佳答案

strings.xml使用%s而不是%.1f

<resources>
    <string name="text_zero">%s stars</string>
    <string name="text_one">1 star</string>
    <string name="text_two">%s stars</string>
    <string name="text_few">%s stars</string>
    <string name="text_many">%s stars</string>
    <string name="text_other">%s stars</string>
</resources>

测试代码

DecimalFormat format = new DecimalFormat("#.#"); // format the number
float rating = getRating();
getContext().getResources()
    .getQuantityString(R.plurals.hotel_card_rating_text, (int) rating, format.format(rating)));

使用复数时要小心。它有自己的问题,请参见下文:

Plural definition is ignored for zero quantity

Issue 8287: PluralRules does not handle quantity "zero"

关于Android 以整数和浮点形式显示复数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39695378/

相关文章:

android - 更改自定义 ListView 中的 TextView 值

android - 将特征添加到android

android - 将 createBitmap 从 Java 转换为 JNI

android - Intent - startActivityForResult

android - React Native Axios 上传图片在 Android 上返回网络错误

java - ListView 中的图像从行跳转到行

安卓设计 : Intentservice causing application not responding

android - fileinputstream 抛出 filenotfoundexception?

android - 更新谷歌播放服务后,应用程序不会在非 4.4 设备上构建

android - 如何覆盖 Activity 中的 getResources