Here is small code to illustrate what I am seeing
float floater = 59.999f; DecimalFormat df = new DecimalFormat("00.0"); System.out.println(df.format(floater));
This prints:
60.0
I would like it to print
59.9
What do I need to do?
DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits.
The default rounding mode of DecimalFormat is RoundingMode. HALF_EVEN . This means that it rounds up, or rounds down if the number is nearer to the next neighbour. When the number is exactly between two neighbours (in your case, 2 and 3), it rounds to the nearest even number (in your case, 2).
DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places.
Add this line before using the DecimalFormat
:
df.setRoundingMode(RoundingMode.DOWN);
Take a look at the other rounding modes and see which one is best for you.
Note : this method works only in JDK 1.6 or above
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With