EN
Python - convert string to integer
0
points
In this article, we would like to show you how to convert string to integer in Python.
Quick solution:
number = "123"
result = int(number)
print(type(result)) # <class 'int'>
1. Practical example using int()
In this example, we simply use int()
to convert the string to the integer.
number = "123"
result = int(number)
print(result) # 123
print(type(result)) # <class 'int'>
Output:
123
<class 'int'>
2. Alternative solution
In this example, we use decimal.Decimal()
to a float number. This solution doesn't round the number with more than 15 decimal places like float()
.
from decimal import Decimal
number = "1.1111111111111111"
result = Decimal(number)
print(result) # 1.1111111111111111
print(type(result)) # <class 'decimal.Decimal'>
Output:
1.1111111111111111
<class 'decimal.Decimal'>