1

According to official java doc,

RoundingMode HALF_EVEN:

Rounding mode to round towards the nearest neighbor unless both neighbors are equidistant, in which case, round towards the even neighbor.

So as this is a case of equidistant neighbours, why is it still rounding off to 6.33 instead of 6.32

public static void main(String[] args) {
    DecimalFormat df = new DecimalFormat("0.00");
    df.setRoundingMode(RoundingMode.HALF_EVEN);
    System.out.println((df.format(6.325)));
}

I am expecting the output of 6.32 for Half_EVEN roundoff but instead it yeilds 6.33.

Any help would be appreciated

Thanks

  • 2
    This is because primitive floating point numbers have limited precision. Using BigDecimal that doesn't have this problem like `System.out.println((df.format(new BigDecimal("6.325"))));` will give you the correct answer of `6.32` – OH GOD SPIDERS Dec 07 '22 at 10:16
  • 1
    @OHGODSPIDERS: That's worthy of an answer, since it presents a solution. – DarkDust Dec 07 '22 at 10:19

1 Answers1

2

Floating point numbers can't represent some numbers exactly (there's lots of questions here on SO dealing with that).

The closest double to 6.325 is 6.32500000000000017763568394002504646778106689453125, and that's why it's rounded up to 6.33.

You can search for things like "double precision floating converter online" for web services that can show you the exact binary representations of floating point numbers.

DarkDust
  • 90,870
  • 19
  • 190
  • 224