Abidi
Abidi

Reputation: 8006

Float and Double for monetary values

I have experimented what is wrong with float and double types, in Java System.out.print(1-.6) prints .4 and the result is a bit unexpected (0.30000000000000004) in case of System.out.print(1-.7). It would be helpful if anyone is able to direct me towards some resources that explain WHY does it happen. I am assuming its not Java specific its something inherently wrong with these types.

Thanks!

Upvotes: 1

Views: 400

Answers (2)

Déjà vu
Déjà vu

Reputation: 28850

As said Vincent the float and double types cannot store values that will not be represented as the sum of 2^-n values (n size depends on the implementation).

Use the BigDecimal class instead.

Upvotes: 1

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

The real types in Java are implementations of IEEE754 single and double precision floating point notation. These are approximations of real numbers rather than exact representations. Some real numbers like 0.8 cannot be represented accurately.

Upvotes: 3

Related Questions