decimal.Decimal.from_float()

from_float(f)

Classmethod that converts a float to a decimal number, exactly.

Note Decimal.from_float(0.1) is not the same as Decimal(‘0.1’). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. That equivalent value in decimal is 0.1000000000000000055511151231257827021181583404541015625.

Note

From Python 3.2 onwards, a Decimal instance can also be constructed directly from a float.

>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_float(float('nan'))
Decimal('NaN')
>>> Decimal.from_float(float('inf'))
Decimal('Infinity')
>>> Decimal.from_float(float('-inf'))
Decimal('-Infinity')

New in version 3.1.

doc_python
2016-10-07 17:31:30
Comments
Leave a Comment

Please login to continue.