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

Output:

    0.05000000000000000277555756156289135105907917022705078125

How to handle this ?

Vikash Singh
  • 13,213
  • 8
  • 40
  • 70
  • 1
    That's not a "garbage value". That's the double precision floating-point representation of 0.05. – awksp Jul 02 '14 at 19:57
  • See also the Java Puzzlers presentation of this (and other) topics: http://www.infoq.com/presentations/Java-Puzzlers – David Conrad Jul 02 '14 at 20:06

2 Answers2

5

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

Convert it to this

BigDecimal b = new BigDecimal("0.05");

when you pass 0.05 it is by default double value and that is how it gets represented in double

jmj
  • 237,923
  • 42
  • 401
  • 438
  • `0.5` is a `double` not a `float`, as is `0.05`. This converts a String. but if you want to convert a double, use `valueOf(double)` – Peter Lawrey Jul 02 '14 at 19:57
  • @Peter yes you are right about `double`, corrected thanks and +1 – jmj Jul 02 '14 at 20:00