Python - convert string to float

0 points
Created by:

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


<class 'float'>


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


<class 'decimal.Decimal'>

Alternative titles

  1. Python - convert string to decimal number
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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.

❤️💻 🙂