1

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!

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Abidi
  • 7,846
  • 14
  • 43
  • 65
  • http://docs.sun.com/source/806-3568/ncg_goldberg.html – Adam Vandenberg Dec 04 '10 at 17:12
  • 1
    http://stackoverflow.com/questions/285680/representing-monetary-values-in-java gives the best recommendation. Use BigDecimal. – robert_x44 Dec 04 '10 at 17:16
  • 1
    I find it a source of constant amusement that, of the 1,123,061 questions currently on SO, 67% of them have to do with floating point inaccuracies :-) – paxdiablo Dec 04 '10 at 17:17
  • thats good, I am not the only one then. Cheers for the links. – Abidi Dec 04 '10 at 17:37
  • possible duplicate of [Why not use Double or Float to represent currency?](http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) – Jonik Feb 17 '11 at 19:21

2 Answers2

3

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.

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
  • Thanks Vincent! I amgonna read that page, too many scary symbols though :( – Abidi Dec 04 '10 at 17:31
  • Found this one quite helpful. http://ravisharda.blogspot.com/2010/09/floating-point-basics-made-easy.html – Abidi Dec 12 '10 at 19:25
1

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.

Déjà vu
  • 28,223
  • 6
  • 72
  • 100
  • Cheers, yeah I did read that thread about using BigDecimal for monetary calculations, was just curious about these types. – Abidi Dec 04 '10 at 17:29