NumberFormat object loses value when converted to string
I'm curious why the conversion to string loses the decimal, but when I pass the object directly, it retains its value.
//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);
+3
source to share
1 answer
Use setMinimumFractionDigits(int)
(which controls the minimum number of digits displayed) and setMaximumFractionDigits(int)
(which controls the maximum number of displayed digits) -
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);
Output
10.0
and this gives the same output
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);
Since , you want it not to lose the decimal. And I suppose you always want one (and only one) decimal place.
+2
source to share