Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numberFormat object loses value when converted to a string

Tags:

java

I'm curious why converting to a string loses the decimal but when I pass in the object directly it maintains it's 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); 
like image 690
Geoff Dawdy Avatar asked Mar 23 '26 18:03

Geoff Dawdy


1 Answers

Use setMinimumFractionDigits(int) (which controls the minimum displayed number of digits), 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 is

10.0

and this produces 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 to not lose the decimal. And, I assume you always want one (and only one) decimal place.

like image 168
Elliott Frisch Avatar answered Mar 26 '26 07:03

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!