Languages
[Edit]
EN

Python - convert string to float

0 points
Created by:
Lennox-A
425

In this article, we would like to show you how to convert string to float in Python.

Quick solution:

number = "1.234"
result = float(number)

print(type(result))  # <class 'float'>

 

1. Practical example using float()

In this example, we simply use float() to convert the string to the float number.

number = "1.1111111111111111"
result = float(number)

print(result)        # 1.1111111111111112
print(type(result))  # <class 'float'>

Output:

1.1111111111111112
<class 'float'>

Note:

When you have more than 15 decimal places, the float() will round the number. If you don't want your number to be rounded, you can use alternative solution from the section below.

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'>

Python - string (popular problems)

Python - convert string to float
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join