使用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)