Convert a number using atof

前端 未结 2 453
天涯浪人
天涯浪人 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:49

    Just for future reference - this is what I ended up using:

    import locale
    from locale import atof
    
    def convert(string, thousands_delim = '.', abbr = 'de_DE.UTF-8'):
        ''' Converts a string to float '''
    
        locale.setlocale(locale.LC_ALL, abbr)
        try:
            number = atof("".join(string.split(thousands_delim)))
        except ValueError:
            number = None
    
        return number
    


    You call it like

    number = convert('17.907,08')
    print(number)
    # 17907.08
    

    ... or for English numbers:

    number = convert('1,000,000', abbr = 'en_US')
    print(number)
    # 1000000.0
    

提交回复
热议问题