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

后端 未结 3 1559
逝去的感伤
逝去的感伤 2020-11-27 07:37

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 ru

相关标签:
3条回答
  • 2020-11-27 08:21

    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')
    
    0 讨论(0)
  • 2020-11-27 08:24

    You can use locale.atof

    import locale
    locale.atof('12.3')
    

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

    0 讨论(0)
  • 2020-11-27 08:43

    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)
    
    0 讨论(0)
提交回复
热议问题