代码之家  ›  专栏  ›  技术社区  ›  gregturn

Jython:将文本解析为包含逗号的浮点

  •  1
  • gregturn  · 技术社区  · 17 年前

    txt = "1,903.44"
    value = float(txt) # This fails due to ',' in string
    

    4 回复  |  直到 14 年前
        1
  •  3
  •   Rob    17 年前
    txt = "1,903.44"
    value = float(txt.replace(',', ''))
    

    如果您需要本地化,这将不会真正起作用,但如果您知道逗号是分隔符,它会起作用。

        2
  •  3
  •   Mark Ransom    17 年前

    使用 locale.atof() locale.setlocale(locale.LC_ALL, '') .

        3
  •  3
  •   thesamet    17 年前

    您可以去掉逗号:

    txt = txt.replace(',', '')
    value = float(txt)
    
        4
  •  0
  •   Community Mohan Dere    9 年前

    我个人在处理货币价值时会使用十进制软件包,以避免 well-documented pitfalls 使用浮点时发生的错误。

    from decimal import Decimal
    txt = txt.replace (',', '')
    value = Decimal(txt)
    

    正如其他海报所指出的,只有当您的地区使用“,”作为分隔符时,这才有效,但应该会让您朝着正确的方向前进。