Parse a string to an int or float in Python

1 min read

Parsing a string to an integer can be done using Python's built-in int() function.

s = '12'
i = int(s)

print(i, type(i))
# 12 <class 'int'>

Parsing a string to a float can be done using the built-in float() function.

s = '12.73'
f = float(s)

print(f, type(f))
# 12.73 <class 'float'>

To parse a string with a decimal point to an integer you'll need to convert it to a float first.

s = '12.73'
i = int(float(s))

print(i, type(i))
# 12 <class 'int'>

Note that the above method does not round the number up to 13, it simply removes the decimal numbers. If you want to round the number you will need to use Python's built-in round() function to round the float before converting it to an integer.

s = '12.73'
r = round(float(s))
i = int(r)

print(i, type(i))
# 13 <class 'int'>

If you want to round a float to a specific amount of decimal numbers you can pass the number of decimals as a second argument to the round() function.

s = '12.7278204'
r = round(float(s), 2)

print(r, type(r))
# 12.73 <class 'float'>

Just be aware that there are some inherent limitations with floating point accuracy in Python.

Author picture
Rhett Trickett

Founder at Able

@rhett RhettTrickett rhetttrickett

Join the discussion

Able is a developer community where people build their coding knowledge and careers.

Join with GitHub Join with Twitter