Convert String to Double in Python | 3 Methods Explained With Example

Convert String to Double in Python| 3 Methods Explained

Do you know how to convert a string to a double in Python? If you are new to Python, this is one of the first things you should learn. Otherwise, you are going to run into errors the first time you try to do math with user input.

The short answer: use float(). Python does not have a separate double type. Its float is already a 64-bit double, so float("3.14") gives you a double.

price = float("19.99")
print(price + 1)    # 20.99

Python is different from languages like C or Java. You do not have to declare a data type when you create a variable. Python works out the type from the value you give it. To understand how that works, check out our guide on different kinds of Python data types.

But there is one catch. Anything that comes from input(), a text file, or a CSV file arrives as a string, even if it looks like a number. From that background, this article was written. Here you will learn why we need to convert strings to doubles, three methods to do it, and how to handle the strings that refuse to convert.

TL;DR: Convert String To Double In Python

AspectSummary
Why Conversion Is Needed?Python treats all user input as strings, so arithmetic on it causes a TypeError. You have to convert before you calculate.
Double In Python?Python does not have a double data type. It uses float, which is the same thing as double precision (64 bits).
Method 1: Using float()The most common approach. It converts a numeric string into a floating-point number in a simple and fast way.
Method 2: Using The Decimal ModuleUsed for high-precision work like money. It avoids the rounding errors that floating-point numbers have.
Method 3: Using NumPyConverts a string to a 64-bit float. It is common in machine learning, scientific computing, and NumPy workflows.

What Is A Double In Python?

If you are coming from C, C++, or Java, you know two decimal types: float (32 bits) and double (64 bits). Python keeps it simple and has only one, called float. But under the hood, Python's float is stored as a 64-bit double. So in Python, "float" and "double" mean the same thing.

You can check this yourself:

import sys

price = 19.99
print(type(price))                 # Python calls it float

print(sys.float_info.mant_dig)     # 53 bits of precision, same as a C double
print(sys.float_info.dig)          # Digits you can always trust
print(sys.float_info.max)          # Largest value it can hold

Output:

<class 'float'>
53
15
1.7976931348623157e+308

The 53 bits of precision is exactly what a double has in C and Java. It gives you about 15 to 17 significant digits.

Language32-bit type64-bit type
C / C++ / Javafloatdouble
PythonNone built in (NumPy has float32)float

So when an assignment says "convert the string to a double," in Python that means convert it to a float.

Why Should We Convert String To Double In Python?

In Python, when a programmer takes input using the built-in input() function, the input is captured as a string. This means that no matter what the user enters (a number, text, or anything else), Python treats it as a sequence of characters.

Python is a dynamically typed language. Variable types are not declared beforehand, and Python has no way of knowing what the user will type. So it plays safe and hands you the input as text.

Here is a simple example to show the type of user input.

# Taking user input
message = input("Please enter a message: ")
pincode = input("Please enter the recipient pincode: ")

# Displaying the captured input
print("Message:", message, " ", type(message))
print("Pincode:", pincode, " ", type(pincode))

Output:

Please enter a message: Happy Birthday
Please enter the recipient pincode: 20774
Message: Happy Birthday   <class 'str'>
Pincode: 20774   <class 'str'>

From the output, we can see that both the message and the pincode are received as strings, even though the pincode is made of digits.

Now, if a beginner takes a number as input and directly does arithmetic on it, Python will raise an error. Let us see that with one example.

p = input("Enter Number: ")  # Taking user input
p = p + 10                   # Trying to add
print("Result:", p)          # Printing the value

Output:

Enter Number: 25
Traceback (most recent call last):
  File "type_error.py", line 2, in <module>
    p = p + 10                   # Trying to add
        ~~^~~~
TypeError: can only concatenate str (not "int") to str

The output shows a TypeError, because we are trying to add a string value to an integer. The same thing happens with decimal numbers. The fix is to convert the string first:

p = input("Enter Number: ")  # Taking user input
p = float(p) + 10            # Convert first, then add
print("Result:", p)          # Printing the value

Output:

Enter Number: 25
Result: 35.0

This is the reason we have to convert string values to double in Python. That TypeError on input() catches a lot of people. If it's stuck in your own code, we can help you debug your Python.

How To Check A Valid String Before Conversion In Python?

Before converting a string to a float, it is a good idea to check whether the string is valid. If it is not, float() raises a ValueError and your program stops. Any time the string comes from a user or a file, you should make this check, no matter how experienced you are.

To validate a string before converting it to a double, we use a try-except block. Let us check it.

def check(value):
    try:
        float(value)        # If conversion is possible
        return True
    except ValueError:      # If there is any invalid string
        return False


print("Conversion Possible For 12.34? ", check("12.34"))    # Possible
print("Conversion Possible For 12.3.4? ", check("12.3.4"))  # Not possible

Explanation Of The Program:

  • Inside a function, a try-except block checks the conversion.
  • We try to convert the string to a float. If it works, the function returns True.
  • If the conversion is not possible, a ValueError is caught and the function returns False.

Output:

Conversion Possible For 12.34?  True
Conversion Possible For 12.3.4?  False

Did you know fact about converting strings to float in Python

Comparison Table Between Try-Except Vs. Regex For Float Validation

To validate a string for float() conversion, we have shown the try-except method. Apart from try-except, a regex (regular expression) check is also used as an alternative.

CriteriaTry-Except For Float ValidationRegex For Float Validation
SpeedFastMedium
StrictnessFlexibleStrict
ComplexityLowHigh
ReadabilityClearDense
Error HandlingAutomaticManual

What does "flexible" versus "strict" really mean? Here is a small test that runs both checks on the same strings.

import re

# Only allow: optional sign, digits, optional decimal part
pattern = re.compile(r'[+-]?(\d+\.?\d*|\.\d+)')

def check_try(value):
    try:
        float(value)
        return True
    except ValueError:
        return False

def check_regex(value):
    return pattern.fullmatch(value) is not None

for text in ["12.34", "-7", "12.3.4", "1e5", "nan", "inf", " 42 ", "1_000"]:
    print(f"{text!r:10} try-except: {check_try(text)!s:6} regex: {check_regex(text)}")

Output:

'12.34'    try-except: True   regex: True
'-7'       try-except: True   regex: True
'12.3.4'   try-except: False  regex: False
'1e5'      try-except: True   regex: False
'nan'      try-except: True   regex: False
'inf'      try-except: True   regex: False
' 42 '     try-except: True   regex: False
'1_000'    try-except: True   regex: False

Both agree on the normal cases. But float() also accepts "1e5", "nan", "inf", extra spaces, and even "1_000". If your program should only accept plain numbers like 12.34, a regex check is the safer choice. For most homework, try-except is enough.

What Are The Methods To Convert String To Double In Python?

Now it is time to jump to the core of the article. Here are the functions you can use to convert a string to a double. We start with float(), since it is the built-in function you will use most. After that, we cover two more.

1. Using float() Function

The simplest method is the built-in float() function, which converts a string to a floating-point number. It stores the number in base 2 (binary), with a fixed number of bits for the fraction part and the exponent.

# _pi is currently a String
_pi = "3.14159265359"
value = float(_pi)
print("Type of Pi:", value, " ", type(value))

Steps Of The Program:

  • First, a normal string is declared with a decimal value inside it.
  • Then we use the syntax float(variable_name).
  • It converts the string and stores the value in a new variable.
  • When we print the variable, we can see the type has changed.

Output:

Type of Pi: 3.14159265359   <class 'float'>

From the output, we can see that the class is now float. Since Python's float is a 64-bit double, the string is now converted to a double value.

2. Using Decimal Module

After float(), the Decimal module is the next option. It is used the same way, but it stores the number in base 10, the way we write numbers on paper. That gives you exact decimal values without the small rounding errors of float. It is the right choice for money.

from decimal import Decimal

value_str = "3.14159"
value = Decimal(value_str)
print(value, " ", type(value))

Steps Of The Program:

  • We first import the Decimal class from the decimal module.
  • A string variable is stored in the program.
  • We store the decimal value using the syntax Decimal(variable_name). Note the capital D.
  • Then we print the type to see the change.

Output:

3.14159   <class 'decimal.Decimal'>

The output shows the class is now decimal.Decimal. Keep in mind that a Decimal is not a float. It is slower, and you cannot mix it with floats in the same calculation. But it is exact.

3. Using NumPy Library

The NumPy library is mostly used in machine learning and data science, as it has more advanced numerical functions. If you're exploring Python for AI and ML, read our article on reasons to learn Python for machine learning. NumPy is another good way to convert a string to a double.

import numpy as np

golden_ratio = "1.61803398875"
phi = np.float64(golden_ratio)
print(phi, " ", type(phi))

Steps Of The Program:

  • We first import NumPy as np, which makes it easy to use many times.
  • We take a string value with a decimal number.
  • Using the syntax np.float64(variable_name), we convert the value.
  • Then we print the type of the new variable.

Output:

1.61803398875   <class 'numpy.float64'>

From the output, you can see that float64 is the new type. The "64" in the name tells you it is a 64-bit double. You can now use the value for addition or any other arithmetic without an error.

Which Method Should You Use?

MethodResult TypeBest ForNeeds Import?
float()float (64-bit double)Everyday use, user input, most assignmentsNo
Decimal()DecimalMoney and anything that must be exactYes (standard library)
np.float64()numpy.float64NumPy arrays, data science, MLYes (install NumPy)

Multiple Usage Of float() Function While Converting String To Double

The float() method is used far more than any other method, and it is really simple to use. That is the reason we are diving a bit deeper into it. Real strings are often messy, with signs, spaces, commas, and currency symbols. Let us check the following program.

import re
import locale

# Example 1: Convert a positive decimal string to double
print("Example 1: ", float("+1.23"))

# Example 2: Convert a negative integer string with extra whitespace to double
print("Example 2: ", float("  -99887\n"))

# Example 3: Convert a special string to double (negative infinity)
print("Example 3: ", float("-Infinity"))

# Example 4: Convert a string with a comma decimal to double
value = "3,14"
value = value.replace(",", ".")
print("Example 4: ", float(value))

# Example 5: Remove the currency symbol and commas, then convert to double
print("Example 5: ", float(re.sub(r"[^\d.\-]", "", "$1,234.56")))

# Example 6: Convert a scientific notation string to double
print("Example 6: ", float("5.7E6"))

# Example 7: Convert a locale-aware string to double
locale.setlocale(locale.LC_NUMERIC, "de_DE.UTF-8")
print("Example 7: ", locale.atof("1.234,56"))

Output:

Example 1:  1.23
Example 2:  -99887.0
Example 3:  -inf
Example 4:  3.14
Example 5:  1234.56
Example 6:  5700000.0
Example 7:  1234.56

Explanation Of The Conversion:

  • Positive Decimal String: A string with a plus sign converts without issues. The plus mark is simply dropped.
  • Negative Integer String: The minus sign stays after the conversion, and a .0 is added at the end. Spaces and newlines around the number are ignored.
  • Negative Infinity: Special strings like "-Infinity", "inf", and "nan" are valid. You get the special float values -inf, inf, and nan.
  • String With Comma Decimal: In some regions, a comma is used as the decimal separator. Since float() does not accept a comma, we replace the comma with a dot first.
  • Currency Symbol: Sometimes a string includes a currency symbol and thousands commas. We use a regex to remove everything except digits, the dot, and the minus sign, and then convert.
  • Scientific Notation String: You can convert scientific notation strings too. Just give the number with the e, and float() does the rest.
  • Locale-Aware String: These are numbers formatted by the rules of a specific country. In Germany, 1.234,56 means one thousand two hundred thirty-four point five six. The locale package handles it. Note that the locale has to be installed on your computer, or setlocale() will raise an error.

Common Errors And How To Fix Them

Here are the strings that break float() most often in student code, with the exact message Python gives.

tests = ["", "abc", "12.3.4", "1,234.56", "$50", None]

for value in tests:
    try:
        float(value)
    except (ValueError, TypeError) as error:
        print(f"{type(error).__name__}: {error}")

Output:

ValueError: could not convert string to float: ''
ValueError: could not convert string to float: 'abc'
ValueError: could not convert string to float: '12.3.4'
ValueError: could not convert string to float: '1,234.56'
ValueError: could not convert string to float: '$50'
TypeError: float() argument must be a string or a real number, not 'NoneType'
InputWhy It FailsFix
"" (empty)The user pressed Enter without typing anythingCheck for an empty string, or use try-except
"abc"Not a number at allUse try-except and ask again
"12.3.4"Two decimal pointsUse try-except
"1,234.56"Thousands commatext.replace(",", "")
"$50"Currency symbolRemove the symbol first
NoneNot a string, so you get a TypeErrorCheck for None before converting

You can wrap all of these fixes into one small helper function and reuse it:

def to_double(text, default=None):
    """Convert a string to a float. Return default if it cannot be converted."""
    if text is None:
        return default
    cleaned = text.strip().replace(",", "").replace("$", "")
    try:
        return float(cleaned)
    except ValueError:
        return default


print(to_double("42.5"))
print(to_double("  $1,234.56 "))
print(to_double(""))
print(to_double("abc", default=0.0))
print(to_double(None, default=0.0))

Output:

42.5
1234.56
None
0.0
0.0

For more errors like these, see our list of common Python errors in student assignments.

How To Convert A List Or A pandas Column To Double?

In real programs, you rarely convert just one string. More often, you have a whole list of them, or a column in a table.

Converting A List Of Strings

prices = ["19.99", "5.50", "100", "0.75"]

# Option 1: list comprehension
doubles = [float(p) for p in prices]
print(doubles)

# Option 2: map()
doubles = list(map(float, prices))
print(doubles)

print("Total:", sum(doubles))

Output:

[19.99, 5.5, 100.0, 0.75]
[19.99, 5.5, 100.0, 0.75]
Total: 126.24

Both options give the same result. The list comprehension is easier to read, and map() is a little shorter.

Converting A pandas Column

When you load a CSV file with pandas, a number column can come in as text if even one cell has a word in it, like "unknown". Use pd.to_numeric() to fix it.

import pandas as pd

df = pd.DataFrame({"item": ["Pen", "Book", "Bag", "Lamp"],
                   "price": ["2.50", "12.99", "unknown", "30"]})

print(df["price"].dtype)      # str (or object in older pandas) means text

# errors="coerce" turns anything that is not a number into NaN
df["price"] = pd.to_numeric(df["price"], errors="coerce")

print(df["price"].dtype)
print(df)

Output:

str
float64
   item  price
0   Pen   2.50
1  Book  12.99
2   Bag    NaN
3  Lamp  30.00

The column is now float64, and the word "unknown" became NaN (not a number). If you are sure every value is a clean number, df["price"].astype(float) works too, but it raises an error on the first bad value.

What Are Some Python Float Precision Limitations?

You have now seen how to convert strings to floats. But there are some limits of float precision you should remember.

  • A Python float uses binary (base 2), so some decimal values cannot be stored exactly.
  • Because of that, small rounding errors happen. 0.1 + 0.2 does not give exactly 0.3.
  • If you repeat a calculation many times in a loop, these small errors can add up.
  • You may see unexpected trailing digits when you print the result.
  • A float is only reliable to about 15 significant digits.

Here is the problem, and two ways to deal with it.

from decimal import Decimal

# float: fast, but stored in binary
print(float("0.1") + float("0.2"))
print(float("0.1") + float("0.2") == 0.3)

# Decimal: exact, as long as you start from a string
print(Decimal("0.1") + Decimal("0.2"))
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))

# Rounding a float for display
total = float("0.1") + float("0.2")
print(round(total, 2))
print(f"{total:.2f}")

Output:

0.30000000000000004
False
0.3
True
0.3
0.30

If you only need a clean number for display, round it. Our guide to rounding numbers in Python covers the options. If the math itself has to be exact, like money, use Decimal and always create it from a string, not from a float.

What Are The Scenarios Where You Might Need To Convert A String To A Double?

Before ending the topic, here are the places where this conversion comes up most.

Data Parsing

If you read data from external sources, you often get it in string format. To work on it, you have to change it to a double or another number format.

Mathematical Computation

Before any math, every string value in the process has to be converted. One leftover string will crash the calculation.

File I/O

When you read from a text or CSV file, the data comes in as strings. If the file has numeric values you need for calculations, convert those strings to doubles first.

API Responses

Some APIs send numbers as strings, especially prices. You need to convert them to doubles before you can process them.

Command-Line Arguments

When a script accepts command-line arguments, they are received as strings in sys.argv. If they are supposed to be numbers, you need to convert them.

Conclusion

Converting strings to double (floating-point) values in Python is necessary whenever you handle user input or numeric data from files.

The main method is the built-in float() function, which converts a string that holds a number into a floating-point value. Python's float is already a 64-bit double, so that is all you need most of the time.

For situations where precision is very important, the Decimal module comes in handy. And NumPy and pandas give you tools to convert whole arrays and columns at once.

Key Takeaways:

  • Python has no separate double type. Its float is a 64-bit double.
  • Input from input(), files, and command-line arguments arrives as a string, so you must convert it before doing math.
  • float() is the best everyday function to convert a string into a double.
  • float() handles signs, spaces, scientific notation, and inf/nan, but not commas or currency symbols.
  • Wrap the conversion in try-except so a bad string does not crash your program.
  • Along with float(), there are Decimal() for exact values and np.float64() for NumPy work.

Frequently Asked Questions

1. How do I convert a string to a double in Python?

Use the built-in float() function, for example float("3.14"). Python's float is a 64-bit double-precision number, so the result is a double.

2. Does Python have a double data type?

No. Python only has float, and it is stored as a 64-bit double, the same as double in C or Java. There is no separate 32-bit float in standard Python.

3. What is the difference between float and double in Python?

There is none. In languages like C and Java, float is 32 bits and double is 64 bits. In Python, the single float type is 64 bits, so it is a double.

4. Why do I get "ValueError: could not convert string to float"?

The string is not a valid number. Common causes are an empty string, letters, a thousands comma like "1,234", or a currency symbol. Clean the string first, or wrap the conversion in a try-except block.

5. How do I convert a string with commas to a double?

Remove the commas first: float("1,234.56".replace(",", "")) gives 1234.56. If the comma is the decimal separator, as in "3,14", replace it with a dot instead.

6. Should I use float() or Decimal()?

Use float() for general math, science, and most assignments. Use Decimal() when the result has to be exact, such as money, because float can give tiny rounding errors like 0.1 + 0.2 = 0.30000000000000004.