2016-09-26 55 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

啊..!好吧,我想上面的代碼將與您的機制一起工作,只是通過將值轉換爲靜態資源的一些變化,你可以實現你想要的。 –