MCPcopy Index your code
hub / github.com/python/cpython / from_float

Method from_float

Lib/_pydecimal.py:627–669  ·  view source on GitHub ↗

Converts a float to a decimal number, exactly. Note that 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.

(cls, f)

Source from the content-addressed store, hash-verified

625
626 @classmethod
627 def from_float(cls, f):
628 """Converts a float to a decimal number, exactly.
629
630 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
631 Since 0.1 is not exactly representable in binary floating point, the
632 value is stored as the nearest representable value which is
633 0x1.999999999999ap-4. The exact equivalent of the value in decimal
634 is 0.1000000000000000055511151231257827021181583404541015625.
635
636 >>> Decimal.from_float(0.1)
637 Decimal('0.1000000000000000055511151231257827021181583404541015625')
638 >>> Decimal.from_float(float('nan'))
639 Decimal('NaN')
640 >>> Decimal.from_float(float('inf'))
641 Decimal('Infinity')
642 >>> Decimal.from_float(-float('inf'))
643 Decimal('-Infinity')
644 >>> Decimal.from_float(-0.0)
645 Decimal('-0')
646
647 """
648 if isinstance(f, int): # handle integer inputs
649 sign = 0 if f >= 0 else 1
650 k = 0
651 coeff = str(abs(f))
652 elif isinstance(f, float):
653 if _math.isinf(f) or _math.isnan(f):
654 return cls(repr(f))
655 if _math.copysign(1.0, f) == 1.0:
656 sign = 0
657 else:
658 sign = 1
659 n, d = abs(f).as_integer_ratio()
660 k = d.bit_length() - 1
661 coeff = str(n*5**k)
662 else:
663 raise TypeError("argument must be int or float.")
664
665 result = _dec_from_triple(sign, coeff, -k)
666 if cls is Decimal:
667 return result
668 else:
669 return cls(result)
670
671 def _isnan(self):
672 """Returns whether the number is not actually one.

Callers 4

__new__Method · 0.45
_convert_otherFunction · 0.45
_convert_for_comparisonFunction · 0.45

Calls 6

strFunction · 0.85
absFunction · 0.85
_dec_from_tripleFunction · 0.85
bit_lengthMethod · 0.80
clsClass · 0.50
as_integer_ratioMethod · 0.45

Tested by

no test coverage detected