
Convert a float to a Decimal object in Python
We can convert a float to a Decimal object in Python like this.
from decimal import Decimal
d1 = Decimal(-7.8)
d2 = Decimal('-7.8')
print(d1) # -7.79999999999999982236431605997495353221893310546875
print(d2) # -7.8
print(type(d1)) # <class 'decimal.Decimal'>
a1 = d1 / 3
a2 = d2 / 3
print(a1) # -2.599999999999999940788105353
print(a2) # -2.6
print(type(a1)) # <class 'decimal.Decimal'>
The Decimal object is declared with a float or string value. As showed in the above example, the Decimal whose argument is a float is not exactly represented as -7.8 but d2
, taking a string argument, is exactly represented.
The Decimal supports the exact calculation like $7.8 \div 3 = 2.6$.
Comments
Powered by Markdown