Python Glossary Русский

all Python 3Numbers & mathfunction

float.hex

hex

Return a hexadecimal string — a lossless representation of the float; inverse of float.fromhex().

Syntax

x.hex()

Only floats have this method — integers use the built-in hex(), and bytes.hex() is an unrelated thing. Since repr of a float already round-trips in CPython, .hex() is not about preserving the value but about seeing the significand and the exponent explicitly: it is how you notice that 0.1 is stored slightly above one tenth. The output is always normalised — one digit before the point, a power of two after p.

Examples

print((3.5).hex())                          # → 0x1.c000000000000p+1
print((1.0).hex())                          # → 0x1.0000000000000p+0
print((0.1).hex())                          # → 0x1.999999999999ap-4
print((-2.0).hex())                         # → -0x1.0000000000000p+1
print((0.0).hex())                          # → 0x0.0p+0
print(float.fromhex((0.1).hex()) == 0.1)    # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy