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


Question

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

I just want to know how to parse a float str to a float, and (separately) an int str to an int.

1
2058
6/5/2019 3:20:06 PM

Accepted Answer

>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
2418
12/19/2008 1:54:51 AM

def num(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon