DEV Community

Cover image for When you should use Decimal over float in Python
Jordan Kalebu
Jordan Kalebu

Posted on • Updated on

When you should use Decimal over float in Python

How it began?

This week I was dealing with something that required me to store data in AWS Dynamo and I found something interesting which lead me to write this piece of article.

Here is what happened?

I was trying to store float values to the aws dynamo table but it didn't well it raised a Type Error that
inexact numeric for data I was trying to solve.

Understood why (0.1+0.2) != 0.3

After a bit of googling, I came to realize that python does not store exact floating numbers but with tons of decimal other decimal precision(this has to do with the design of the language itself)

Here an example

>>> 1.1 + 1.3
2.4000000000000004
Enter fullscreen mode Exit fullscreen mode

what can we do now?

Python has got you covered, there is a built-in module called decimal which is built on top of float-point data types allowing you to have exactly decimal numbers

Here an example

>>> from decimal import Decimal
>>> Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
Enter fullscreen mode Exit fullscreen mode

As we can see 0.1 in python is nothing but 0.1 with tons of decimals, to express 0.1 as 0.1 we have to pass it as string
to our Decimal function just as shown below;

>>> from decimal import Decimal
>>> Decimal('0.1')
Decimal('0.1')
>>> Decimal('0.1') + Decimal('0.2') == Decimal('0.3')
True
Enter fullscreen mode Exit fullscreen mode

As we can see now 0.1 is presented in exact values, and with this trick I was able to effictively store my float values in the aws lambda smoothly.

Other areas to use Decimal instead of float ?

  1. Accounting Application

When you're dealing with accounting calculation which is probably going to involve calculation with decimal point use Decimal points instead of float values for more accurate and precision in your financial calculation

  1. Converting Decimal to Fraction

When you're writing a program which in some ways do the conversion of decimal numbers to integer fraction, you don't wanna use float, it will screw you up;

Just to put it into action try converting a float value 0.35 to integer fraction

>>> (0.35).as_integer_ratio()
(3152519739159347, 9007199254740992)
Enter fullscreen mode Exit fullscreen mode

Using decimal instead

>>> Decimal('0.35').as_integer_ratio()
(7, 20)
Enter fullscreen mode Exit fullscreen mode

Well that's all I have got for today, you can keep in touch with me on Twitter kalebu for more tricks

Gota any other places you think we should be using Decimal instead of float, Please share in the comment box below;

I also write an in-depth Python tutorial at kalebujordan.dev

Top comments (2)

Collapse
 
alphaolomi profile image
Alpha Olomi

Enlightening!

Collapse
 
kalebu profile image
Jordan Kalebu

Thank you, Phillipe