Python Reference ยท Numbers and Binary Data
Python float methods
Reference for Python float methods: is_integer(), as_integer_ratio(), hex(), fromhex(), conjugate(), plus how binary floating point explains the surprising results.
A Python float is a 64-bit binary floating-point number. Its few methods mostly expose that binary representation: the exact fraction it stores, its hexadecimal form, and whether it has a fractional part.
Floats can only store sums of powers of two, so most decimals such as 0.1 are stored as the nearest representable value. The methods below show exactly what is stored.
(2.5).is_integer() # False (0.5).as_integer_ratio() # (1, 2)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
| Method | Description |
|---|---|
float.is_integer() |
True if the value is finite and has no fractional part. |
float.as_integer_ratio() |
Returns (numerator, denominator) with denominator > 0, in lowest terms, equal to the stored value exactly. |
float.hex() |
Returns the exact value as a hexadecimal string such as '0x1.8000000000000p+1'. |
float.fromhex(s) |
Class method. Parses a string produced by hex() (also 0x forms without the fraction). |
float.conjugate(), .real, .imag |
Number protocol: returns itself, with imag equal to 0.0. |
Raises: OverflowError from as_integer_ratio() on infinity, ValueError on NaN, and ValueError from fromhex() for invalid text.
Usage notes
is_integer()tests the value, not the type.(4.0).is_integer()isTrue, but4.0is still afloat. Infinity and NaN returnFalse.as_integer_ratio()shows the truth.0.1is not one tenth; it is a fraction with a power of two as the denominator, which is why0.1 + 0.2 != 0.3.- Use
decimalorFractionfor exact money and ratios, andmath.isclose()to compare floats. hex()andfromhex()round-trip exactly, and show every bit of the mantissa and exponent, which a decimal string hides.- Literals:
2.5.is_integer()works, but(2.5).is_integer()reads better. - Not the same as
round()orint().int(2.7)truncates to2;is_integer()only reports. - Integers have similar methods: see int methods.