6

I'm trying to add decimal numbers a decimal number and it works correctly but when I do 1.1 + 0.1 I get 1.2000000000000002 but all I want it to equal to is 1.2. When I do 1.0 + 0.1 I get 1.1 which is perfect but i don't get that for 1.1 + 0.1. So is there a way that I can get rid of the 000000000000002 from 1.2000000000000002?

Thanks.

user2387537
  • 361
  • 3
  • 9
  • 17

3 Answers3

7

As has been stated countless times, 0.1 cannot be represented exactly in IEEE 754 floating point. You can read all about why in What Every Computer Scientist Should Know About Floating-Point Arithmetic or The Floating Point Guide

You can trucate or round the value:

>>> round(1.1+.1,2)
1.2
>>> "%.*f" % (1, 1.1+.1 )
'1.2'
>>> s=str(1.1+.1)
>>> s[0:s.find('.')+2]
'1.2'

If you want exact representation of those values, consider using the Decimal module:

>>> import decimal
>>> decimal.Decimal('1.1')+decimal.Decimal('.1')
Decimal('1.2')

Note that you need to start with the string representation of your float, '0.1' since 0.1 is not exactly representable in binary in IEEE floating point:

>>> decimal.Decimal(.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')

To then get a string representation back after you calculate, you can use str:

>>> str(sum(map(decimal.Decimal,['.1','.1','.5','.5'])))
'1.2'

Another alternative is to use a rational number library such as Fractions:

>>> from fractions import Fraction as Fr
>>> Fr(11,10)+Fr(1,10)
Fraction(6, 5)

With that result, you will still need to round, truncate, or use an arbitrary precision arithmetic package to get an exact number (depending on the inputs...)

dawg
  • 98,345
  • 23
  • 131
  • 206
3

You can try string formatting, documentation here.

>>> "%0.2f" % float(1.1 + 0.1)
'1.20'

Or Even:

>>> "%0.1f" % float(1.1 + 0.1)
'1.2'

As to why, it is explicitly described on PEP 327 here.

0

This is the literal answer to your question:

float(str(1.1 + 0.1)[0:3])

If you're interested in the "why" of the problem then refer to the links provided in the question comments.

Bleeding Fingers
  • 6,993
  • 7
  • 46
  • 74