Custom locale configuration for float conversion

前端 未结 3 1363
滥情空心
滥情空心 2021-02-19 22:43

I need to convert a string in the format \"1.234.345,00\" to the float value 1234345.00.

One way is to use repeated str.repl

3条回答
  •  星月不相逢
    2021-02-19 23:21

    If you pop open the source code for locale, you can see that there is a variable called _override_localeconv (which seems to be for testing purposes).

    # With this dict, you can override some items of localeconv's return value.
    # This is useful for testing purposes.
    _override_localeconv = {}
    

    Trying the following does seem to override the dictionary without changing the entire locale, though it probably has some unintended consequences, especially since changing locales isn't threadsafe. Be careful!

    import locale
    
    locale._override_localeconv["thousands_sep"] = "."
    locale._override_localeconv["decimal_point"] = ","
    
    print locale.atof('123.456,78')
    

    Try it online!

提交回复
热议问题