-1

Can someone explain to me why:

33.8 * 100 # => 3379.999999999995

but

23.8 * 100 # => 2380.0
sawa
  • 165,429
  • 45
  • 277
  • 381
Doctore
  • 61
  • 3
  • 2
    You can no more represent 0.1 exactly in binary than you can 1/3 in decimal: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – duffymo Sep 14 '15 at 14:57
  • The question is not clear. Do you mean "why the answers are different"? It is because `33.8` and `23.8` are different. – sawa Sep 14 '15 at 15:04
  • @duffymo - but both 33.8 and 23.8 contain "0.1", yet 23.8*100 returns the "expected" value. Why? – Doctore Sep 14 '15 at 15:13
  • Read the article. This is how floating point numbers work in IEEE. – duffymo Sep 14 '15 at 15:14
  • Although your question is about the other factor, it is more accurately a duplicate of this question than of the one that was chosen, and my answer provides some elements to explain why one constant gets rounded back to an integral value and the other doesn't: http://stackoverflow.com/a/18036308/139746 – Pascal Cuoq Sep 14 '15 at 17:12

1 Answers1

4

Floating-point numbers cannot precisely represent all real numbers, and floating-point operations cannot precisely represent true arithmetic operations, this leads to many surprising situations.

I advise to read: https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

You may want to use BigDecimal to avoid such problems.

spickermann
  • 100,941
  • 9
  • 101
  • 131
  • BigDecimal won't represent 1/3 exactly. No help there. – duffymo Sep 14 '15 at 15:15
  • 1
    It would return the right numbers for the examples in the question. – spickermann Sep 14 '15 at 15:17
  • spickerman - Thanks for your quick answer. A couple more questions:If floating-point numbers are so inaccurate for simple arithmetic operations, what's the point of the Float class? Also, is there a way to predict which floating numbers would be "inaccurate" and which would return the expected result, as 23.8*100 did? – Doctore Sep 14 '15 at 15:18
  • @Doctore: Floats are way faster and need less memory than BigDecimal, and very often you don't need the exact precision. – spickermann Sep 14 '15 at 15:21