Similar to the
int data type,
floats also have several additional methods useful in various scenarios.
For example, you can directly check if the float number is actually an integer with
>>> (5.9).is_integer() False >>> (-9.0).is_integer() True
Integer values might be preferred over floats in some cases and you can convert a
float to a
tuple matching a fraction with integer values:
>>> (-5.5).as_integer_ratio() (-11,2) # -11 / 2 == -5.5
As floats' numbers representation in binary is not really human-friendly and tends to be lengthier with precision, the hexadecimal format is preferred. Such hexadecimal representations have the form:
[sign]['0x']int['.' fraction]['p' exponent] # e.g 0x1.8000000000000p+0 -> 1.5 # 1.5 in decimal is 1.8 in hex # 0 - sign # int - str of hex. digits of integer part # fraction - same for fractional part
To convert a float number to a hex string you can use the hex() function.
>>> (3.14).hex() '0x1.91eb851eb851fp+1' >>> float.hex(1.5) '0x1.8000000000000p+0'
The reverse can be achieved with the fromhex() class method:
>>> float.fromhex('0x1.91eb851eb851fp+1') 3.14 >>> float.fromhex('0x1.8000000000000p+0') 1.5