2

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?

Arslan Munir
  • 417
  • 5
  • 10

2 Answers2

1

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'
Netwave
  • 40,134
  • 6
  • 50
  • 93
1

@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
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114