0

Can someone tell me what I'm missing here? This is using Python 2.7.11:

print float(148.95)
print float(148.95)*100
print int(float(148.95)*100)

Why does this print:

148.95
14895.0
14894 <--- Shouldn't this be 14895?
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Shaun
  • 1,581
  • 2
  • 16
  • 35

1 Answers1

1

148.95 is not a number that can be exactly represented using floating point. The number internally stored is actually 148.94999999999998863131622783839702606201171875. When you multiply by a hundred, you get 14894.999999999998181010596454143524169921875. When you convert that to integer, it cuts off the .999... and you're left with 14894.

If you want a data type that can exactly represent numbers with at least two decimal places of precision, consider using Decimal.

>>> from decimal import Decimal
>>> x = Decimal("148.95")
>>> print x
148.95
>>> print x*100
14895.00
>>> print int(x*100)
14895
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • The comment that I heard was, "floating point number like little pile of sand on the ground. Each time you pick it up and move it around, you lose a little sand and pick up a little dirt." Also remember that, when you *print* it, you are seeing a character, base-*ten*, representation of an internal, base-*two*, floating-point value. These characteristics are typical of all computer languages, and are basically unavoidable. "It's just how the thing works ..." (And by "the thing," I mean, "the computer!") – Mike Robinson Jun 24 '16 at 14:35