What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Convert String to Double in Python (3 Easy Methods)

  • Oct 27, 2022
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Mradula Mittal
Convert String to Double in Python (3 Easy Methods)

Python is a dynamically typed language. Here, the interpreter predicts the data type of the Python variable based on the type of value assigned to that variable.

When you take a user input in Python, it is always received as a string. It is taken as a string, whether the input is an integer, a list, a decimal number, or another. As a result, you must explicitly convert the string to the desired value in order to conduct the required operations on it. This is also known as Type Conversion.

Type Conversion can be performed for different data types, like converting integers to strings or vice-versa. In this article, we're going to discuss methods on how to convert a string to double in Python.

But before moving forward, let's learn about strings and doubles in Python.

What is Double in Python?

According to the IEEE 754 standard, all platforms represent Pyhton float numbers as 64-bit "double-precision" values. (It seems similar to the double in C language). Python does not have an in-built double data type (int, string, and float are in-built data types).

But it includes float data type, which represents a floating-point value (but here with more precision). It allows you to count double since float is also expressed with a decimal point.

What's the difference between float and double? A float has 7 decimal digits of precision and 32 bits of storage. A double contains 15 decimal digits of precision and takes up 64 bits. Also, the float has less precision than double.

Let's take an example of double in Python:

# Program: Double in Python

# a double data type
num = 45.3365859965333
print(num, " type: ", type(num))

# a float variable
f = 45.4564
print(f, " type: ", type(f))

 

Output:

45.3365859965333  type:  <class 'float'>
45.4564  type:  <class 'float'>

 

Note how in Python both the types show 'float', even when the precision for both numbers is different.

What are Strings in Python?

A string is the most often used data type in any language. It is a sequence of characters (including numbers, alphabets, special characters, and even white spaces). In Python, any sequence of characters enclosed within quotation marks (single or double) is a string.

Let's take an example:

# Program: String in Python

# a character
char = "m"
print(char, " type: ", type(char))
# sequence in double quotation
string = "Convert String to Double in Python"
print(string + " type: ", type(string))

# sequence in single quotation
s = "FavTutor"
print(s + " type: ", type(s))

 

Output:

m  type:  <class 'str'>
Convert String to Double in Python type:  <class 'str'>
FavTutor type:  <class 'str'>

 

From the output, you can note that the data type is "string" for each of the sample variables created above.

What is the need to Convert a String to Double?

As mentioned earlier, Python accepts input in the form of strings, be it an integer or another number. Let's check the statement out:

# Program: Taking input from Python

num = input("Enter a number: ")
print("The input is: ", num, " and type: ", type(num))

 

Output:

Enter a number: 45.879841313
The input is:  45.879841313  and type:  <class 'str'>

 

Now you've confirmed the data type of the input. As you already know, the data type must be compatible with the operation being performed else it will produce an error.

So, while you're at it, let's confirm this as well:

num = input("Enter a number: ")
print("The input is: ", num, " and type: ", type(num))

# operating on input
print(num - 10)

 

Output:

Enter a numbers: 45.48984661
The input is:  45.48984661  and type:  <class 'str'>
Traceback (most recent call last):
  File ".\temp.py", line 5, in <module>
    print(num - 10)
TypeError: unsupported operand type(s) for -: 'str' and 'int'

 

Note the produced TypeError also depicts that the operation (generally performed with int or floats) isn't supported by your input format. Hence the need to convert strings to other data types arises.

How to Convert String to Double in Python?

 There are many methods for Type Conversion of String to Double in python. Let's check out a few of them:

01) Using float()

You can convert a string to double in Python using the float() method. This method requires only one parameter and returns the input as float (here, double). This is also a common method to convert a string to float in Python. (Remember that Python uses float as double!)

Example:

# Program: Convert string to double in Python using float()

num = input("Enter a number: ")
print("The input is: ", num)

# calling float()
num = float(num)
print("num: ", num, " type: ", type(num))

# Also operating on input
print("Performing operation: ", num - 10)

 

Output:

Enter a number: 45.1365464
The input is:  45.1365464
num:  45.1365464  type:  <class 'float'>
Performing operation:  35.1365464

 

I've converted the type and also depicted the use of the converted data type by performing the subtracting operation. Note that the float function only works with floating-point representations. It returns an error when a non-float representation is passed to it as a parameter. Let's check it out:

# Program: Convert string to double in Python using float()

num = input("Enter a numbers: ")
# let the input be - '45,25.4545211'
print("The input is: ", num)

# calling float()
num = float(num)
print("num: ", num, " type: ", type(num))

# Also operating on input
print("Performing operation: ", num - 10)

 

Output:

Enter a numbers: 45,25.4545211
The input is:  45,25.4545211
Traceback (most recent call last):
  File ".\temp.py", line 8, in <module>
    num = float(num)
ValueError: could not convert string to float: '45,25.4545211'

 

You can either replace the ',' with another '.' or use try-catch to catch this error.

Although float() is easy to use and remember, note that if the string number contains more than 15 significant digits, float() will round it up.

Example:

# Program: Convert string to double in Python using float()

num = 45.1315465465387834654

# calling float()
num = float(num)
print("num: ", num, " type: ", type(num))

 

Output:

num:  45.131546546538786  type:  <class 'float'>

 

Note how the number got rounded up in output. To avoid this anomaly, Python provides us with another function, known as the Decimal() function. Let's learn more about it.

02) Using Decimal()

Python decimal module offers a Decimal() function that converts a string to double in Python. It takes the string as an input parameter and converts it to a decimal type. This can store and represent the number with the required accuracy.

Let's check out how to use Python's Decimal() function to convert a string to a double-precision number:

# Program: Convert string to double in Python using Decimal()

# import Decimal from decimal module
from decimal import Decimal

num = "153.4564504586313134586"
# calling Decimal()
num = Decimal(num)
print("num: ", num, " type: ", type(num))

 

Output:

num:  153.4564504586313134586  type:  <class 'decimal.Decimal'>

 

Note how the Decimal() function doesn't round off the values for float representation of more than 15 significant digits.

Other than converting string to double in Python, the Decimal() function is also called to bring precision to the number, for example:

# Program: Convert string to double in Python using Decimal()

# import Decimal from decimal module
from decimal import Decimal

num = 153.4564504586313134586
# calling Decimal()
num = Decimal(num)
print("num: ", num, " type: ", type(num))

 

Output:

num:  153.45645045863130917496164329349994659423828125  type:  <class 'decimal.Decimal'>   

 

The Decimal() function has provided more accuracy to the already presented number.

Also, similar to the float() function, the Decimal() function also takes only valid float representations of a number. That is it gives Invalid Operations error when an argument like 1,465.6556 is passed to it as an argument.

03) Using pandas.to_numeric()

While working with Python, you'll also come across DataFrames. DataFrames are one of the most commonly utilized data structures in modern data analytics. This brings us to another use of converting string to double in Python.

Before moving on to the conversion, let's take a look at what are DataFrames? DataFrames are data structures that arrange data into a 2-dimensional table of rows and columns (similar to a spreadsheet). These provide a flexible and easy manner of storing and working with data.

Now, that you've learned about DataFrames, let's move on to creating a dataframe in Python:

import pandas as pd

languages = {
    "Course": ["Spark", "PySpark", "Hadoop", "Python", "pandas", "Oracle", "Java"],
    "Fee": [20000, 25000, 26000, 22000, 24000, 21000, 22000],
    "Duration ": ["30.645", "40.23", "35.25", "40.5656", "60.155", "50", "55"],
    "TimeSlot": [11.8, 23.7, 13.4, 15.7, 12.5, 25.4, 18.4],
}
df = pd.DataFrame(languages)
print(df.dtypes)

 

You need to import the pandas' module for creating this Dataframe. Two functions are used here to create the dataframe:

  1. DataFrame(): This function is used to create a dataframe.
  2. dtypes: This returns a series of the datatype of the each column.

Here, df is the name of the variable used to reference our dataframe.

Output:

Course       object
Fee            int64
Duration      object
TimeSlot     float64
dtype: object

 

The dtypes returns 'object' dtype for columns with mixed types. Note that dtype is an attribute of DataFrame.

Now that you've created a dataframe, let's move on to converting one of these columns to float. Since the column "Fee" is not a mixed type. let's try converting this to float in Python-

The to_numeric() function converts the passed argument to a numeric type. By default, it returns 'int64' or 'float64' as per the data supplied.

import pandas as pd

languages = {
    "Course": ["Spark", "PySpark", "Hadoop", "Python", "pandas", "Oracle", "Java"],
    "Fee": [20000, 25000, 26000, 22000, 24000, 21000, 22000],
    "Duration ": ["30.645", "40.23", "35.25", "40.5656", "60.155", "50", "55"],
    "TimeSlot": [11.8, 23.7, 13.4, 15.7, 12.5, 25.4, 18.4],
}
df = pd.DataFrame(languages)
print(df.dtypes)

df["Fee"] = pd.to_numeric(df["Fee"], downcast = "float")
print(df.dtypes)

 

Output:

Course        object
Fee            int64
Duration      object
TimeSlot     float64
dtype: object
Course        object
Fee          float64
Duration      object
TimeSlot     float64
dtype: object

 

Note how the dtype for the "Fee" column has changed from 'int64' to 'float64'.(Although to be converted into double this should be float64 or float128, it also has float32 with it.)

To know more about ways to convert string to Python check out 6 Ways to Convert String to Float in Python.

Conclusion

In this article, we've discussed ways to convert string to double in Python. Also, we've taken an insight into DataFrames in Pandas and converted dtype of a column to double (float64). If you need more precision you can also use numpy's float128.

As mentioned earlier, Python's float has double type precision, hence you can also convert string to float in Python to achieve the purpose.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Mradula Mittal
I'm Mradula Mittal, a tech community enthusiast with a knack for content writing. Always eager to learn more about Python and Machine Learning. Having an analytical brain, I'm particular about my research and writing. I live by the motto "the more you share, the more you learn" and being a techie, it's fun to learn, create and share.