Convert Python strings into floats explicitly using the comma or the point as separators

How can I explicitly tell python to read a decimal number using the point or the comma as a decimal separator? I don’t know the localization settings of the PC that will run my script, and this should not influence my application, I only want to say:

f = read_float_with_point("3.14")

or

f = read_float_with_comma("3,14")

I think that writing

def read_float_with_comma(num):
    return float(num.replace(",", ".")

is not secure, because I don’t know the locale settings!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

because I don’t know the locale settings

You could look that up using the locale module:

>>> locale.nl_langinfo(locale.RADIXCHAR)
'.'

or

>>> locale.localeconv()['decimal_point']
'.'

Using that, your code could become:

import locale
_locale_radix = locale.localeconv()['decimal_point']

def read_float_with_comma(num):
    if _locale_radix != '.':
        num = num.replace(_locale_radix, ".")
    return float(num)

Better still, the same module has a conversion function for you, called atof():

import locale

def read_float_with_comma(num):
    return locale.atof(num)

Method 2

You can use locale.atof

import locale
locale.atof('12.3')

http://docs.python.org/2/library/locale.html

Method 3

You can use babel to parse decimals in local formats:

>>> parse_decimal('1,099.98', locale='en_US')
Decimal('1099.98')
>>> parse_decimal('1.099,98', locale='de')
Decimal('1099.98')


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x