Reputation: 2018
I have this code
private static DecimalFormat df2 = new DecimalFormat(".00");
System.out.println(df2.format(14.3445));
the correct answer for this should be 14.35 but i get 14.34 Why ?
The conversion should be 14.3445 -> 14.345 -> 14.35
Upvotes: 0
Views: 137
Reputation: 415
14.34 is correct, as it is closer to 14.3445 that 14.35:
|14.3445 - 14.34| = 0.0045
while
|14.3445 - 14.35| = 0.0055
Upvotes: 3
Reputation: 15622
from the API https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html
Rounding
DecimalFormat provides rounding modes defined in RoundingMode for formatting. By default, it uses RoundingMode.HALF_EVEN.
and https://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html#HALF_EVEN
public static final RoundingMode HALF_EVEN
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for RoundingMode.HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for RoundingMode.HALF_DOWN if it's even.
Since the second 4 (third fraction digit) is even it is not changed which leads to "round down" for the second fraction digit.
Upvotes: 2