
Python Decimal - Basic usage
The "decimal", which is an instance of Decimal class, is a float-like object in Python.
from decimal import Decimal
d = Decimal(4.5)
print(d) # 4.5
print(type(d)) # <class 'decimal.Decimal'>
You can input a float or string to the Decimal argument. But the float argument may create an inaccurate object as follows.
from decimal import Decimal
d1 = Decimal('0.1')
d2 = Decimal(0.1)
print(d1) # 0.1
print(d2) # 0.1000000000000000055511151231257827021181583404541015625
Arithmetic operations
Decimal numbers can be calculated correctly.
from decimal import Decimal
f = 0.1 * 3
print(f) # 0.30000000000000004
d = Decimal('0.1') * 3
print(d) # 0.3
Addition, subtraction, multiplication, division of decimals:
from decimal import Decimal
d1 = Decimal('1.5')
d2 = Decimal('0.6')
print(d1 + d2) # 2.1
print(d1 - d2) # 0.9
print(d1 * d2) # 0.90
print(d1 / d2) # 2.5
Mix of float and string argument
from decimal import Decimal
print(Decimal(1.5) / Decimal(0.6)) # 2.500000000000000092518585385
print(Decimal('1.5') / Decimal(0.6)) # 2.500000000000000092518585385
print(Decimal(1.5) / Decimal('0.6')) # 2.5
print(Decimal('1.5') / Decimal('0.6')) # 2.5
Comments
Powered by Markdown