使用atof转换数字

发布于 2021-01-29 16:39:13

在中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()为了什么吗?

关注者
0
被浏览
51
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您的数字中不能有多个点(.)或逗号(,),因为这两个符号用于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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看