Alex Rivera | Logout

Java BigDecimal precision problems

Asked 2012-03-20T21:36:30.163
15

I know the following behavior is an old problem, but still I don't understand.

System.out.println(0.1 + 0.1 + 0.1);    

Or even though I use BigDecimal

System.out.println(new BigDecimal(0.1).doubleValue()
    + new BigDecimal(0.1).doubleValue()
    + new BigDecimal(0.1).doubleValue());

Why this result is: 0.30000000000000004 instead of: 0.3?

How can I solve this?

Edit
Report

1 Answer

6

This is not a problem of Java, but rather a problem of computers generally. The core problem lies in the conversion from decimal format (human format) to binary format (computer format). Some numbers in decimal format are not representable in binary format without infinite repeating decimals.

For example, 0.3 decimal is 0.01001100... binary But a computer has a limited "slots" (bits) to save a number, so it cannot save all the whole infinite representation. It saves only 0.01001100110011001100 (for example). But that number in decimal is no longer 0.3, but 0.30000000000000004 instead.

answered 2012-03-20T21:45:53.747

Your Answer