How do I parse a string to a float or int?

后端 未结 29 2779
醉话见心
醉话见心 2020-11-21 04:43

In Python, how can I parse a numeric string like \"545.2222\" to its corresponding float value, 545.2222? Or parse the string \"31\" t

29条回答
  •  梦毁少年i
    2020-11-21 05:02

    I am surprised nobody mentioned regex because sometimes string must be prepared and normalized before casting to number

    import re
    def parseNumber(value, as_int=False):
        try:
            number = float(re.sub('[^.\-\d]', '', value))
            if as_int:
                return int(number + 0.5)
            else:
                return number
        except ValueError:
            return float('nan')  # or None if you wish
    

    usage:

    parseNumber('13,345')
    > 13345.0
    
    parseNumber('- 123 000')
    > -123000.0
    
    parseNumber('99999\n')
    > 99999.0
    

    and by the way, something to verify you have a number:

    import numbers
    def is_number(value):
        return isinstance(value, numbers.Number)
        # will work with int, float, long, Decimal
    

提交回复
热议问题