Android在整数和浮点数中显示复数形式

时间:2016-09-26 05:39:29

标签: android

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

对于.0等浮点值,移除1.0, 2.0 etc.但是.5的值显示浮点值2.5 3.5 etc.

这可以使用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)));
            }

2 个答案:

答案 0 :(得分:1)

你可以试试下面的片段,这是非常典型的

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

快乐的编码!

答案 1 :(得分: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"