In Python, how can I parse a numeric string like \"545.2222\"
to its corresponding float value, 545.2222
? Or parse the string \"31\"
t
I am surprised nobody mentioned regex because sometimes string must be prepared and normalized before casting to number
import re
def parseNumber(value, as_int=False):
try:
number = float(re.sub('[^.\-\d]', '', value))
if as_int:
return int(number + 0.5)
else:
return number
except ValueError:
return float('nan') # or None if you wish
usage:
parseNumber('13,345')
> 13345.0
parseNumber('- 123 000')
> -123000.0
parseNumber('99999\n')
> 99999.0
and by the way, something to verify you have a number:
import numbers
def is_number(value):
return isinstance(value, numbers.Number)
# will work with int, float, long, Decimal