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

kev*_*nlu 67 python type-conversion

如何在Python中将字符串转换123,456.908为float 123456.908

Kar*_*tel 125

...或者不是将逗号视为要过滤的垃圾,我们可以将整个字符串视为浮动的本地化格式,并使用本地化服务:

from locale import atof, setlocale
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
Run Code Online (Sandbox Code Playgroud)

  • 对于脚本来说很好,对于库来说很糟糕:`扩展模块永远不应该调用setlocale()` (13认同)
  • @wanderer:不推荐使用的是`atof`*内置字符串*方法.我在这里使用的是来自`locale`标准库模块的函数`atof`,它根本不被弃用. (12认同)
  • 这就是明星导入不好的原因 - 我建议你编辑这个以导入所需的或更好的命名空间,如`locale.atof` (5认同)
  • 到目前为止,大多数pythonic和直观的方式.+1 (3认同)
  • 如果示例中同时包含小数点和数字分组字符,我将对此答案投票... (2认同)
  • 这很好,但需要注意的一点是,似乎千位分隔符(en_US 中的“,”,de_DE 中的“.”)被完全忽略,并且像“1,23,,.4,56”这样的字符串` 无误地转换为 `123.456`(在 en_US 中)。 (2认同)
  • 11.5 年后,我最初版本的答案似乎完全无法接受(尽管显然没有人认为适合否决它,哪怕一次)——所以我完全重写了它。我现在彻底解释“locale”模块的作用、如何找出正确的区域设置以及这种方法的局限性 - 全文给出了详细的示例。 (2认同)

zee*_*kay 100

只需删除,with replace():

float("123,456.908".replace(',',''))
Run Code Online (Sandbox Code Playgroud)

  • 这取决于区域设置.9 988 776,65€在法国9.988.776,65€在德国$ 9,988,776.65在美国 (12认同)
  • 这种极其危险的替代品将[在世界的一半地区失败](https://en.wikipedia.org/wiki/Decimal_separator#/media/File:DecimalSeparator.svg),另一半在中国。还有美国。欧洲、非洲、俄罗斯、南美,使用`,`作为小数点分隔符 (2认同)

hay*_*ayj 9

如果您不知道语言环境并且想要解析任何类型的数字,请使用parseNumber(text)函数。它并不完美,但考虑到大多数情况:

>>> parseNumber("a 125,00 €")
125
>>> parseNumber("100.000,000")
100000
>>> parseNumber("100 000,000")
100000
>>> parseNumber("100,000,000")
100000000
>>> parseNumber("100 000 000")
100000000
>>> parseNumber("100.001 001")
100.001
>>> parseNumber("$.3")
0.3
>>> parseNumber(".003")
0.003
>>> parseNumber(".003 55")
0.003
>>> parseNumber("3 005")
3005
>>> parseNumber("1.190,00 €")
1190
>>> parseNumber("1190,00 €")
1190
>>> parseNumber("1,190.00 €")
1190
>>> parseNumber("$1190.00")
1190
>>> parseNumber("$1 190.99")
1190.99
>>> parseNumber("1 000 000.3")
1000000.3
>>> parseNumber("1 0002,1.2")
10002.1
>>> parseNumber("")

>>> parseNumber(None)

>>> parseNumber(1)
1
>>> parseNumber(1.1)
1.1
>>> parseNumber("rrr1,.2o")
1
>>> parseNumber("rrr ,.o")

>>> parseNumber("rrr1rrr")
1
Run Code Online (Sandbox Code Playgroud)

  • 请包含该代码作为您答案的一部分。答案需要是独立的,以防止链接腐烂使答案变得无用。 (2认同)

Luc*_*llo 7

如果你有一个逗号作为小数分隔符和点作为千位分隔符,你可以这样做:

s = s.replace('.','').replace(',','.')
number = float(s)
Run Code Online (Sandbox Code Playgroud)

希望它会有所帮助


Auf*_*ind 5

那这个呢?

 my_string = "123,456.908"
 commas_removed = my_string.replace(',', '') # remove comma separation
 my_float = float(commas_removed) # turn from string to float.
Run Code Online (Sandbox Code Playgroud)

简而言之:

my_float = float(my_string.replace(',', ''))
Run Code Online (Sandbox Code Playgroud)


Qui*_*ieh 5

针对不同货币格式的更好解决方案:

def text_currency_to_float(text):
    t = text
    dot_pos = t.rfind('.')
    comma_pos = t.rfind(',')
    if comma_pos > dot_pos:
        t = t.replace(".", "")
        t = t.replace(",", ".")
    else:
        t = t.replace(",", "")
    return float(t)
Run Code Online (Sandbox Code Playgroud)

此函数通过检查逗号在字符串中从右侧出现的位置来检测逗号是否为千位分隔符或句点是否为小数分隔符。(前提是数字的小数部分不能使用千位分隔符。)