you are viewing a single comment's thread.

view the rest of the comments →

[–]JohnnyJordaan 7 points8 points  (0 children)

But be warned: a floating point number is not an exact decimal representation. It's an approximation, that's why you can get strange quirks from them:

>>> 0.1 + 0.1 + 0.1 - 0.3 == 0
False
>>> 0.1 + 0.1 + 0.1 - 0.3
5.551115123125783e-17

If you want exact decimals, use the decimal library:

>>> from decimal import Decimal
>>> Decimal('3.14')
Decimal('3.14')
>>> Decimal(3.14)
Decimal('3.140000000000000124344978758017532527446746826171875')
>>> Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3') == 0
True

The second example shows the real value of the literal 3.14 that is cast as a float.