Python Glossary Русский

all Python 3Numbers & mathfunction

float.fromhex

hex

Class method: parse a hexadecimal string (as produced by float.hex()) back into a float.

Syntax

float.fromhex(s)

Every digit after the point is hexadecimal and the 0x prefix is optional, so '3.5' here is not three and a half but 3 + 5/16 = 3.3125. The method exists for one job: moving a float between programs bit for bit; for parsing ordinary user text you want float(s). A malformed string raises ValueError rather than quietly returning zero.

Examples

print(float.fromhex('0x1.8p+1'))            # → 3.0
print(float.fromhex('0x1.0p+0'))            # → 1.0
print(float.fromhex('-0x1p-1'))             # → -0.5
print(float.fromhex('3.5'))                 # → 3.3125
print(float.fromhex((0.1).hex()) == 0.1)    # → True
print(float.fromhex('hello'))               # → ValueError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy