1

So I have this code

public String getRounded(double amount) {
    DecimalFormat df = new DecimalFormat("0.00");
    df.setRoundingMode(RoundingMode.HALF_UP);
    System.out.println(df.format(amount));
    System.out.println(amount);
    return df.format(amount);
}

I've added those two lines to see the difference and this is an example of what they display.

The output is this for example:

1.25

1.255

Why does this happen? Isn't the point of HALF_UP to round up? I've tried with CEILING and it does round up, although that's not what I want in this case.

Thank you

1 Answers1

7

double is lying to you. System.out.println is lying to you.

amount is not exactly 1.255. It is actually 1.25499999999999989341858963598497211933135986328125, which is less than the exact real number 1.255.

Rounding that with HALF_UP returns, correctly, 1.25.

If you care about fine distinctions like this, you will need to use BigDecimal from the beginning.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413