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

后端 未结 29 2784
醉话见心
醉话见心 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条回答
  •  野的像风
    2020-11-21 04:44

    You need to take into account rounding to do this properly.

    I.e. int(5.1) => 5 int(5.6) => 5 -- wrong, should be 6 so we do int(5.6 + 0.5) => 6

    def convert(n):
        try:
            return int(n)
        except ValueError:
            return float(n + 0.5)
    

提交回复
热议问题