2016-09-26 75 views
2

我的目标是显示“1星”“2.5星”“3星”等文本。Android显示整数和浮点数的复数

是删除.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))); 
      } 

回答

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"

+0

“零”量不存在问题 - 这只是对数量如何工作以及它们的目的是什么的常见误解。例如,“零”,“一”和“两”不直接映射到确切的数字0,1和2,因此它们不被所有语言使用(即使数字显然可以被所有语言使用语言)。 – LoPoBo

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 

快乐编码!

+0

我必须用壁画有许多语言。 –

+1

啊..!好吧,我想上面的代码将与您的机制一起工作,只是通过将值转换为静态资源的一些变化,你可以实现你想要的。 –