Python - Numeric Decimal Type

Introduction

The decimal object, formally known as Decimal.

With decimals, we can have a floating-point value that always retains just two decimal digits.

We can specify how to round or truncate the extra decimal digits beyond the object's cut off.

The decimal type is useful for representing fixed-precision quantities like sums of money.

Demo

from decimal import Decimal 
print( 0.1 + 0.1 + 0.1 - 0.3 )                         # Python 3.3 
print( Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3') )

Result

Here, we create decimal objects by calling the Decimal constructor function in the decimal module.

When decimals of different precision are mixed in expressions, Python converts up to the largest number of decimal digits automatically:

Demo

from decimal import Decimal 
print( Decimal('0.1') + Decimal('0.10') + Decimal('0.10') - Decimal('0.30') )

Result

You can create a decimal object from a floating-point object via a call of decimal.Decimal.from_float(1.25).

Demo

from decimal import Decimal 
print( Decimal(0.1) + Decimal(0.1) + Decimal(0.1) - Decimal(0.3) )

Result

Related Topics