Reputation: 485
I've found that using the decimal format and rounding mode shown behaves unexpectedly with some values
double b = 123.135;
//double b = 1896.675;
//double b = 523.135;
DecimalFormat df = new DecimalFormat(".##");
df.setRoundingMode(RoundingMode.HALF_UP);
System.out.println(b);
String a = df.format(b);
System.out.println(a);
double roundOff = Math.round(b * 100.0) / 100.0;
System.out.println(roundOff);
Produces:
123.135
123.14
123.14
Which I believe to be correct.
While using this value: 1896.675 produces the following:
1896.675
1896.67
1896.68
Which I regard as unexpected - What am I doing wrong here?
Upvotes: 2
Views: 575
Reputation: 607
Problem here is that it is not possible to store all possible fractions in a variable because of the limitations of the binary format. So basically double just approximates the value you entered and thats why rounding errors occure. You can read more about this topic in for example this thread: how does java.math.RoundingMode work?
Long story short, if you want precise rounding use BigDecimal (and the valueOf Function of the BigDecimal class)
Upvotes: 3