Search code examples
javabigdecimaldouble-precision

Issue with java BigDecimal storing garbage value


    BigDecimal b = new BigDecimal(0.05);
    System.out.println(b);

Output:

    0.05000000000000000277555756156289135105907917022705078125

How to handle this ?


Solution

  • The number is strictly correct. This is the exact value 0.05 as a double is. This is because double cannot represent all values exactly and instead must give you the closest representable value. When you print the value, it assumes you want to round it, and hides the representation error. BigDecimal is just showing you what the value really is.

    If you want to convert from a double to a BigDecimal and have it round the way you expect use

    BigDecimal b = BigDecimal.valueOf(0.05);
    

    Another solution is to not use BigDecimal. If you use double with appropriate rounding, you will get the same answer, with a lot less code and much faster code.