如何将带点和逗号的字符串转换为 Python 中的浮点数

新手上路,请多包涵
阅读 578
2 个回答

只需删除 ,replace()

 float("123,456.908".replace(',',''))

原文由 zeekay 发布,翻译遵循 CC BY-SA 3.0 许可协议

…或者不是将逗号视为要过滤掉的垃圾,而是将整个字符串视为浮点数的本地化格式,并使用本地化服务:

 from locale import atof, setlocale, LC_NUMERIC
setlocale(LC_NUMERIC, '') # set to your default locale; for me this is
# 'English_Canada.1252'. Or you could explicitly specify a locale in which floats
# are formatted the way that you describe, if that's not how your locale works :)
atof('123,456') # 123456.0
# To demonstrate, let's explicitly try a locale in which the comma is a
# decimal point:
setlocale(LC_NUMERIC, 'French_Canada.1252')
atof('123,456') # 123.456

原文由 Karl Knechtel 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题