I was playing with datatypes in python.

Every time, when I do

remaining_amount = .1 + .1 + .1 - .3

python gives an exponential result.

I try to do the same with c#

double remainingAmount = .1 + .1 + .1 - .3

It is also giving result in exponential form.

In both cases, the result is 5.55111512312578E-17

But in c#, when I change double to decimal, the result is 0.0

I am unable to understand why this is happening in both languages. And how can I fix this in python?

2 Answers

1
U9-Forward On Best Solutions

@Netwave is correct, as you wanted to fix this in python, the way would be decimal module:

>>> from decimal import Decimal
>>> Decimal('.1') + Decimal('.1') + Decimal('.1') - Decimal('.3')
Decimal('0.0')
>>> float(Decimal('.1') + Decimal('.1') + Decimal('.1') - Decimal('.3'))
0.0
>>> 
1
Netwave On

That is the Python representation of the number, the number is still the same. You can format a string with it for printing purpouses for example:

>>> remaining_amount  = .1 + .1 + .1 - .3
>>> remaining_amount
5.551115123125783e-17
>>> f"{remaining_amount:.50f}"
'0.00000000000000005551115123125782702118158340454102'