Reputation: 14218
There seems to be some inconsistency with the way DecimalFormat
rounds numbers.
new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.US)).format(number)
Here's what's returned for some different number
values.
Why does this happen? And more importantly, how can I get the correct values (0.3 when rounding 0.25 and 0.5 when rounding 0.45)?
Upvotes: 1
Views: 1302
Reputation: 198093
The Javadoc states:
DecimalFormat provides rounding modes defined in RoundingMode for formatting. By default, it uses RoundingMode.HALF_EVEN.
HALF_EVEN
does exactly what you've noticed: it prefers rounding to the nearest even number when it's exactly halfway between two numbers. (This is useful for a number of reasons, primarily because it doesn't bias up or down on average, tending to balance out rounding error.)
Just call setRoundingMode(RoundingMode.HALF_UP)
for the behavior you describe.
Upvotes: 5