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
You should consider the possibility of commas in the string representation of a number, for cases like float("545,545.2222")
which throws an exception. Instead, use methods in locale
to convert the strings to numbers and interpret commas correctly. The locale.atof
method converts to a float in one step once the locale has been set for the desired number convention.
Example 1 -- United States number conventions
In the United States and the UK, commas can be used as a thousands separator. In this example with American locale, the comma is handled properly as a separator:
>>> import locale
>>> a = u'545,545.2222'
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.atof(a)
545545.2222
>>> int(locale.atof(a))
545545
>>>
Example 2 -- European number conventions
In the majority of countries of the world, commas are used for decimal marks instead of periods. In this example with French locale, the comma is correctly handled as a decimal mark:
>>> import locale
>>> b = u'545,2222'
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
'fr_FR'
>>> locale.atof(b)
545.2222
The method locale.atoi
is also available, but the argument should be an integer.