str2float
str2float#
- str2float(num: str) float [source]#
Converts a number represented as a string to a float. Can include suffixes (such as ‘u’ for micro, ‘k’ for kilo, etc.).
- Parameters
num (str) – A string representing a number, optionally with a suffix.
- Returns
The string converted back to its floating point representation.
- Return type
float
- Raises
ValueError – If the argument is malformed or the suffix is not recognized.
Examples
>>> str2float('14.5c') 0.145
Values without suffixes get converted to floats normally.
>>> str2float('2.53') 2.53
If an unrecognized suffix is present, a
ValueError
is raised.>>> str2float('17.3o') ValueError: Suffix 'o' in '17.3o' not recognized. ([-+]?[0-9]+[.]?[0-9]*((?:[eE][-+]?[0-9]+)|[a-zA-Z])?)
Some floats are represented in exponential notation instead of suffixes, and we can handle those, too:
>>> str2float('15.2e-6') 1.52e-7
>>> str2float('0.4E6') 400000.0