Python Decimals

Often times you find yourself trying to perform math on floating point numbers and discover weird intricacies with this data type in python. There are many formatting options, and data manipulations you can do after the fact to get things the way you want, but sometimes you just want this to work the ways it’s supposed to. For instance take the following arithmetic into consideration:

1.5 - 1.4 = .1
1.8 - 1.6 = .2
1.9 - 1.6 = .3

Sounds pretty straightforward right? However, if you attempt to do this in python, you get this strangeness:

1.5 - 1.4
0.10000000000000009
1.8 - 1.6
0.19999999999999996
1.9 - 1.6
0.2999999999999998

Have A Million Dollar Pay Day – Click To Learn How!

Like I mentioned above, there are a lot of ways to work around this with data formatting and configuring the precision of your floating point numbers however you want to. Decimal is so much nicer though:

from Decimal import *
a = Decimal(1.5)
b = Decimal(1.4)
c = Decimal(1.8)
d = Decimal(1.6)
e = Decimal(1.9)
print(a - b)
print(c - d)
print(e - d)

Now this looks like it should. Just like those days in grade school:

print(a - b)
0.1
print(c - d)
0.2
print(e - d)
0.3

Make Money Selling Domain Names

Leave a comment