2

I'm working on a bit of code where I'm implementing half-even rounding. I've been using this post (How to round a number to n decimal places in Java) as a guide and am running tests using the code below on an online Java compiler:

// Java code
public static void main(String []args){
        String precisionString = "#.##";
        double localValue = 265.335;
        DecimalFormat df = new DecimalFormat(precisionString);
        df.setRoundingMode(RoundingMode.HALF_EVEN);
        System.out.println(Double.parseDouble(df.format(localValue)));    
     }

It works fine for most test values, but for the value 265.335, rounding to 2 decimal places returns 265.33 when it should be 265.34.

I tested this out on an online C# compiler and got similar results (C# equivalent below), so I'm thinking this isn't a language bug but rather something to do with how the numbers are being read in binary. I'm not able to figure out exactly what/where the problem is though..

// C# code
public static void Main()
    {
        double a = 265.335;
        var rounded = Math.Round(a, 2, MidpointRounding.ToEven);
        Console.WriteLine(rounded);
    }

Thoughts ?

Andorrax
  • 33
  • 4
  • 3
    `a = 235.335` doesn't actually set `a` to `235.335`. It sets it to the nearest number that has a precise `double` representation. – Dawood ibn Kareem Jan 05 '23 at 00:00
  • 1
    ... which according to [this online calculator](https://www.exploringbinary.com/floating-point-converter/) happens to be `265.33499999999997953636921010911464691162109375`, which is why it got rounded down. – Dawood ibn Kareem Jan 05 '23 at 00:42
  • 1
    In C# just use [decimal type](https://learn.microsoft.com/es-es/dotnet/api/system.decimal?view=net-7.0#remarks) and It would get rounded to 235.34 – Mike93041 Jan 05 '23 at 00:48
  • You can also do `new BigDecimal(265.335)` in Java to see the real floating-point representation of `265.335`. That will match to the one from the above online calculator. You can also use `var bd = BigDecimal.valueOf(265.335); df.format(bd)`, which will achieve you goal. For details, you can refer to javadoc of `BigDecimal` methods I've outlined here. – Dmitry Khamitov Jan 05 '23 at 12:47

0 Answers0