float.fromhex()
A classmethod, called on the type. The 0x prefix is optional, which is the source of its one genuinely nasty surprise.
Demo
fromhex reads the format float.hex produces: a hex mantissa, then p and a power of two. Look hard at the third case. Because the 0x prefix is optional, the string "0.5" is parsed as HEXADECIMAL — the digit after the point is sixteenths, so it means 5/16, or 0.3125. It does not mean one half, and nothing warns you. Anything that is not a valid hex float raises ValueError.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| string | str | yes | A hexadecimal float such as '0x1.8p+0'. The 0x prefix and the p exponent are both optional. Also accepts 'inf', '-inf' and 'nan'. Leading and trailing whitespace is ignored. |
Return value
float — The float the string represents. Raises ValueError if the string is not a valid hexadecimal float.
Common patterns
assert float.fromhex(x.hex()) == x
epsilon = float.fromhex(config["epsilon_hex"])
value = float.fromhex("0x1.91eb851eb851fp+1")
Examples
Pitfalls
float.fromhex('0.5')
float('0.5')
fromhex('0x1p+0')
float.fromhex('0x1p+0')
float.fromhex('0x1p+8') # expected 16**8?
1 * 2 ** 8
float.fromhex('1e5')
float('1e5')
When to use
- Reading back a value written with float.hex
- Exact constants in config files or test fixtures
- Reproducing a precise float from a bug report
- Ordinary decimal text → float(s)
- User input of any kind → the hex-by-default rule will bite
- Exact decimal arithmetic → decimal.Decimal
Notes
FAQ
Because the whole string is hexadecimal, prefix or not. The digit after the point is a count of sixteenths, so 5 means 5/16 = 0.3125. If you meant ordinary decimal text, float() is the function you want.
float.fromhex('0.5') # 0.3125 float('0.5') # 0.5