Search code examples
java-8floating-accuracy

Java Float value round off


I have tried a simple java program to round off the Float value

float value = 0.525f;
System.out.println(Math.round(value * 100.0d) / 100.0f)

Getting Output is - 0.52 But expected is - 0.53

When I debug the value of float value variable it is showing me 0.5249999761581421 something like. I think because of only this reason it is not rounding correctly.

Please help me if anyone knows how to round the float value up to two decimal places.


Solution

  • When converting 0.525f into a double (which implicitely happens in your calculation), 0.5249999761581421 is the nearest double representation. This number will then get rounded down.

    Another issue is that your expression always rounds down (as you just cut off all but the first two decimal places).

    Java has built-in support for rounding numbers in the BigDecimal class.
    For rounding such a number, use:

    String s = String.valueOf(0.525f); // results in "0.525"
    BigDecimal rounded = new BigDecimal(s).setScale(2, RoundingMode.HALF_UP);
    System.out.println(rounded);
    

    which results in 0.53.

    Also note that are different ways of rounding numbers (see Javadoc for RoundingMode).