8 Replies Latest reply: Aug 29, 2013 4:48 AM by jwenting

# Core Java Issue in decimal division....SOS!!!!

Hi People,

I was just wondering the reason for below output generated in java.

double d2 = 0.142;

double d3 = d2/100;

System.out.println(d3);

Output = 0.0014199999999999998

But if i do in calculator i get 0.00142

double d2 = 0.152;

double d3 = d2/100;

System.out.println(d3);

Output = 0.0015199999999999999

But if i do in calculator i get 0.00152

Any help is highly appreciated.

• ###### 1. Re: Core Java Issue in decimal division....SOS!!!!

http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

• ###### 2. Re: Core Java Issue in decimal division....SOS!!!!

Thanks PhHein, the article looks bit complicated. Will spend some time to understand it.

• ###### 3. Re: Core Java Issue in decimal division....SOS!!!!

It boils down to: if you need precision use BigDecimal (overly simplified).

```BigDecimal bd1 = new BigDecimal("0.142");
BigDecimal bd2 = new BigDecimal("100");
BigDecimal bd3 = bd1.divide(bd2);
System.out.println(bd3);
```
• ###### 4. Re: Core Java Issue in decimal division....SOS!!!!

Yeah I am aware of this; but in our system double is been used for some calculation and its been referred by many other places. Need to do impact analysis before i change to BigDecimal.

• ###### 5. Re: Core Java Issue in decimal division....SOS!!!!

You also might want to read up on Java's  'strictfp' reserved word. I don't know if it will help and weather or not it applies to both float and double since I never used it.

• ###### 6. Re: Core Java Issue in decimal division....SOS!!!!

939520 wrote:

You also might want to read up on Java's  'strictfp' reserved word. I don't know if it will help and weather or not it applies to both float and double since I never used it.

Setting  'strictfp' will make no difference. The Goldberg article explains the problem.

If the OP is doing scientific or engineering work then the errors due to the fact that not all decimal values have a finite length binary representation will usually be small enough to be neglected. If the OP is working with money then, even though double has about 14 decimal places, it is unlikely to be acceptable.

• ###### 7. Re: Core Java Issue in decimal division....SOS!!!!

> even though double has about 14 decimal places

Correction. It can *hold* about 15.9 decimal *digits,* in an integral number. It doesn't *have* 'decimal places' at all, it has binary places. The whole point is that binary and decimal places are incommensurable. 0.1 for example is only one decimal place but it is represented by a very large number of binary places.

• ###### 8. Re: Core Java Issue in decimal division....SOS!!!!

there's only one thing to understand: floating point numbers in a computer are not exact, so expect rounding errors.

If you need exact numbers, use integer mathematics.