我的百分比被默认的 java.text.MessageFormat 函数截断,你如何格式化百分比而不损失精度?
例子:
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;
最佳答案
我认为正确的做法如下:
NumberFormat percentFormat = NumberFormat.getPercentInstance();
percentFormat.setMaximumFractionDigits(1);
String result = percentFormat.format(0.125);
它还考虑了内化。例如,在我使用匈牙利语言环境的机器上,我得到了预期的“12.5%”。将 percentFormat 初始化为 NumberFormat.getPercentInstance(Locale.US)
当然会给出“12.5%”。
关于java - 如何使用 java.text.MessageFormat 格式化小数百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/698261/