【问题标题】:Android show plurals in both integer and floatAndroid以整数和浮点数显示复数
【发布时间】:2016-09-26 05:39:29
【问题描述】:

我的目标是显示“1 星”“2.5 星”“3 星”之类的文字。

对于像1.0, 2.0 etc. 这样的浮点值删除.0 但对于.5 的值显示浮点值2.5 3.5 etc.

这样可以用androidplurals吗?

我用过这种方法,但不起作用。 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)));
            }

【问题讨论】:

    标签: android


    【解决方案1】:

    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"

    【讨论】:

    • zeroquantity 没有问题 - 这只是对数量如何工作以及它们的目的的常见误解。例如,zeroonetwo 并不能分别直接映射到确切的数字 0、1 和 2,因此并非所有语言都使用它们(尽管这些数字显然可以被所有人使用)语言)。
    【解决方案2】:

    你可以在sn-p下面试一试,非常典型

    String somePostFixText = "star";
    String output;
    double starCount;
    
    if (starCount > (double)1)
          somePostFixText = somePostFixText+"s";
    
    if(starCount == (long) starCount){
           output = String.format("%d",(long)starCount)+" "+somePostFixText;
    } else {
           output = String.format("%s",starCount)+" "+somePostFixText;
    }
    
    //do whatever you want to do with output variable
    

    编码愉快!

    【讨论】:

    • 啊..!好吧,我想上面的代码也可以与您的机制一起使用,只需通过将值转换为静态资源进行一些更改,您就可以实现您想要的。
    猜你喜欢
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 2011-01-10
    • 1970-01-01
    相关资源
    最近更新 更多