How Do I Parse a String to a Float or Int?
  • How can I convert a str to float?
    "545.2222"  →  545.2222
    
  • How can I convert a str to int?
    "31"        →  31
    
4

30 Answers

>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
7

Python method to check if a string is a float:

def is_float(value):
  try:
    float(value)
    return True
  except:
    return False

A longer and more accurate name for this function could be: is_convertible_to_float(value)

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.