decimal.Decimal
class decimal.Decimal(value='0', context=None)Create a Decimal from a string or int for exact decimal digits, or from a float for the exact binary value.
| Parameter | Description |
|---|---|
value | A string, int, Decimal, or float, or another documented input. Use a string such as '0.1' when you want the decimal tenth. |
context | Optional context used for conversion. The default context applies when this is omitted. |
Returns: A Decimal instance. print uses __str__, which is the coefficient and exponent, not the Decimal(...) constructor form.
Raises
TypeError— Raised by arithmetic that mixes Decimal and float, such as Decimal(1) + 0.1 on Python 3.13.12.InvalidOperation— Raised for an invalid string such as 'nope' when the InvalidOperation trap is enabled. It is a subclass of ArithmeticError.
from decimal import Decimal, InvalidOperation
print(Decimal("0.1"))
print(Decimal(0.1))
print(Decimal(0.1) == Decimal("0.1"))
print(Decimal(1) + Decimal("0.1"))
try:
Decimal(1) + 0.1
except TypeError as err:
print(type(err).__name__)
try:
Decimal("nope")
except InvalidOperation as err:
print(type(err).__name__)Expected output
0.1
0.1000000000000000055511151231257827021181583404541015625
False
1.1
TypeError
InvalidOperationRelated: fractions