Weird decimal output in python

Viewed 111

I am using python3.9 and trying to calculate the following:

17.36-14.76. It is a pretty easy calculation and the output should be 2.6 without any other additional digits.

However, in python3.9 I get the following output:

>>> 17.36-14.76
2.5999999999999996

I know, I can round the result to get the desired output. However, I don't understand why it calculates it in a weird manner because 17.36-14.76 IS NOT 2.5999999999999996, 17.36-14.76 is 2.6.

Are there some weird settings python?

2 Answers

This is because floating point arithmetic on computers uses base-2 to store numbers rather than our familiar base-10. This means that you don't really have 17.36 and 14.76 there (since you cannot represent them exactly in base-2) but actually an approximation:

>>> f'{17.36:.30}'
'17.3599999999999994315658113919'
>>> f'{14.76:.30}'
'14.759999999999999786837179272'
>>>
>>> f'{17.36-14.76:.30}'
'2.59999999999999964472863211995'

Note that a few numbers such as 1/2 and 1/4 are actually exactly representible using base-2:

>>> f'{.25:.30}'
'0.25'

This is why in general you want to use integers instead of floats if you are caring about exact numbers (such as cent values in currencies).

Another possible workaround is to use the Decimal class (which is essentially just integers that memorized the position of their decimal point). It is important to pass strings here rather than floats:

>>> Decimal('17.36') - Decimal('14.76')
Decimal('2.60')

Use Decimal

>>> from decimal import Decimal
>>> result = Decimal(17.36) - Decimal(14.76)
>>> f'{result:.2f}'
'2.60'
Related