本文介紹了如何使用 java.text.MessageFormat 格式化小數(shù)百分比的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
限時送ChatGPT賬號..
我的百分比被默認的 java.text.MessageFormat 函數(shù)截斷,你如何格式化百分比而不損失精度?
My percentages get truncated by the default java.text.MessageFormat function, how do you format a percentage without losing precision?
例子:
String expectedResult = "12.5%";
double fraction = 0.125;
String actualResult = MessageFormat.format("{0,number,percent}", fraction);
assert expectedResult.equals(actualResult) : actualResult +" should be formatted as "+expectedResult;
推薦答案
看起來像這樣:
String actualResult = MessageFormat.format("{0,number,#.##%}", fraction);
...正在工作.
要查看 # 和 % 是如何解釋的,請參閱 java.text.DecimalFormat 的 javadoc.
To see how are the #'s and %'s interpreted, see the javadoc of java.text.DecimalFormat.
編輯 2:是的,國際化是安全的.格式字符串中的點被解釋為小數(shù)分隔符,而不是硬編碼的點.:-)
EDIT 2: And, yes, it is safe for internationalization. The dot in format string is interpreted as a decimal separator, not as a hardcoded dot. :-)
這篇關(guān)于如何使用 java.text.MessageFormat 格式化小數(shù)百分比的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!