fractions.Fraction, Fraction.from_float, Fraction.from_decimal
class fractions.Fraction(numerator=0, denominator=1)
classmethod Fraction.from_float(f)
classmethod Fraction.from_decimal(dec)Build a Fraction from integers, a decimal string, a float, or a Decimal.
| Parameter | Description |
|---|---|
numerator / denominator | A pair of rationals, or a single other_fraction, float, Decimal, or string when denominator is omitted in the documented single-argument forms. |
f / dec | from_float accepts a float. from_decimal accepts a Decimal. Since Python 3.2 the constructor accepts both types directly. |
Returns: A Fraction in lowest terms. print uses the numerator/denominator form, such as 1/10.
Raises
ZeroDivisionError— Raised when the denominator is zero.TypeError / ValueError— Raised for inputs the constructor does not accept, including a malformed string.
- The long fraction printed for Fraction(0.1) is the exact value of the IEEE 754 binary64 number 0.1, measured on Python 3.13.12.
from decimal import Decimal
from fractions import Fraction
print(Fraction(1, 10), Fraction("0.1"), Fraction("1/10"))
print(Fraction(0.1))
print(Fraction(0.1) == Fraction(1, 10))
print(Fraction(0.1) == Fraction.from_float(0.1))
print(Fraction("0.1") == Fraction.from_decimal(Decimal("0.1")))
print(Fraction(1.5) == Fraction(3, 2))Expected output
1/10 1/10 1/10
3602879701896397/36028797018963968
False
True
True
TrueRelated: decimal