numberFormat对象在转换为字符串时丢失值

时间:2014-08-31 22:48:36

标签: java

我很好奇为什么转换为字符串会丢失小数,但是当我直接传入对象时,它会维持它的值。

//set number of decimals at 1 

//This code produces whole numbers even though I set number to 1 decimal point.
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String averageScoreString = number.format(averageScore);
String message = "Average score is: " + averageScoreString

//This code appears to produce the correct number format.
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "Average score is: " + number.format(averageScore); 

1 个答案:

答案 0 :(得分:2)

使用setMinimumFractionDigits(int)(控制最小显示的位数), setMaximumFractionDigits(int)(控制最大值显示的数字数量) -

int averageScore = 10;
NumberFormat number = NumberFormat.getNumberInstance();
number.setMinimumFractionDigits(1);
number.setMaximumFractionDigits(1);
String message = "Average score is: " + number.format((double) averageScore);
System.out.println(message);

输出

10.0

,这会产生相同的输出

NumberFormat number = NumberFormat.getNumberInstance();
number.setMinimumFractionDigits(1);
number.setMaximumFractionDigits(1);
String averageScoreString = number.format(averageScore);
String message = "Average score is: " + averageScoreString;
System.out.println(message);

以来,您希望它输掉小数。并且,我假设你总是想要一个(并且只有一个)小数位。