使用 atof 转换数字

Convert a number using atof

Python 3.5 中,我想使用 locale.atof 和以下代码将德语数字字符串转换为浮点数:


import locale
from locale import atof
locale.setlocale(locale.LC_ALL, 'de_DE')

number = atof('17.907,08')

然而,这引发了一个 ValueError:

ValueError: could not convert string to float: '17.907.08'


为什么?这不正是 atof() 的目的吗?

您的号码中不能有超过一个点 (.) 或逗号 (,),因为这两种符号都会用到通过 atof() 将数字的小数部分与其整数部分分开。

由于 Python 不需要点来正确表示您的号码,因此您应该删除它们并只保留逗号:

import locale
from locale import atof
locale.setlocale(locale.LC_ALL, 'de_DE')

string_nb = '17.907,08'
string_nb = string_nb.replace('.', '')
number = atof(string)

仅供将来参考 - 这是我最终使用的:

import locale
from locale import atof

def convert(string, thousands_delim = '.', abbr = 'de_DE.UTF-8'):
    ''' Converts a string to float '''

    locale.setlocale(locale.LC_ALL, abbr)
    try:
        number = atof("".join(string.split(thousands_delim)))
    except ValueError:
        number = None

    return number


你这样称呼它

number = convert('17.907,08')
print(number)
# 17907.08

... 或英文数字:

number = convert('1,000,000', abbr = 'en_US')
print(number)
# 1000000.0

在 Python 3.10 中按预期工作

>>> from locale import atof
>>> import locale
>>> locale.setlocale( locale.LC_ALL, 'de_DE' )
'de_DE'
>>> atof('17.907,08')
17907.08

使用字符串操作来解析小数是非常脆弱的,应该尽可能避免。使用错误的替换可能会将小数转换为千位,反之亦然