简体   繁体   中英

Issue with java BigDecimal storing garbage value

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

Output:

    0.05000000000000000277555756156289135105907917022705078125

How to handle this ?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM