Convert a number using atof

前端 未结 2 475
天涯浪人
天涯浪人 2021-01-14 04:28

In Python 3.5, I\'d like to convert a German number string to a float using locale.atof with the following code:


import local         


        
2条回答
  •  我在风中等你
    2021-01-14 04:55

    You can't have more than one dot (.) or comma (,) in your number since both of these symbols are used by atof() to separate the decimal part of your number from its integer part.

    Since the dots are not needed for Python to correctly represent your number, you should remove them and only keep the comma:

    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)
    

提交回复
热议问题