How to Convert a String to a Double in Python [7 Ways]

Do you want to convert a string to a double in Python? In this Python tutorial, I will explain “How to Convert a String to a Double in Python” in 7 different ways or techniques with some illustrative examples.

Converting a string to double, or we can say it string to float, is similar in Python. You can use all the methods for the string to float values in Python, also.

I was working on a project where I needed to take user input of their weight and convert a string to a double in Python, so these methods and techniques helped me a lot to get the required result.

These are 7 different methods in Python to convert a string to double.

  • Using float() method.py
  • Using decimal() method.py
  • Using pandas.to_numeric().py
  • Using the ast.literal_eval().py
  • using the numpy.float64().py
  • using np.fromstring().py
  • using astype.py

Convert string to double in Python using float() method

The float() method is used for typecasting in Python, which is the direct way to convert a string to a double in Python. It takes one parameter as an int or string (if only numeric will be there as a string) which you want to convert.

Consider the following example:

original_str = "82.4652"
print("String: " + original_str, type(original_str))

converted = float(original_str)
print("The conversion of string to double is",converted, type(converted))

In this code, we are typecasting the string to double in Python using the float() method and giving original_str its parameter.

READ:  How to Sum Elements in List in Python using For Loop

Output:

String: 82.4652 <class 'str'>
The conversion of string to double is 82.4652 <class 'float'>

Here’s a combined view of the Python script and its output within Visual Studio

How to Convert a String to a Double in Python

How to convert a string to a double in Python using the decimal() method

We are using the decimal() method of the Decimal class in Python. It is used to construct decimal objects. We will use this method to convert the Python string to double.

Here’s a simple example:

from decimal import Decimal
str = "45.98"
print("This is the initial string: " + str, type(str))

conversion = Decimal(str)
print("The conversion of string to double is", conversion, type(conversion))

In this code, str takes a string representing a decimal number, converts it to a decimal object using the decimal() method in Python, and then prints out the converted value along with its type.

Output:

This is the initial string: 45.98 <class 'str'>
The conversion of string to double is 45.98 <class 'decimal.Decimal'>

Displayed below is the Python code alongside its output, captured in Visual Studio

Convert String to Double in Python

Convert Python string to double using the to_numeric() method

The to_numeric() is a built-in method of Pandas Library in Python. It is used to convert the values of a Series (or a DataFrame column) to numeric data types. It can handle various formats, such as integers, floats, and strings representing numbers.

Let’s see an example:

import pandas as pd

Employee_Data = {
    "name": ['William', 'Emma', 'James', 'Charlotte', 'Alexander', 'Olivia', 'Benjamin'],
    "salary": [50000, 60000, 75000, 48000, 90000, 55000, 62000],
    "weight": ['65.2', '70.5', '68.9', '72.3', '67.8', '69.6', '71.1'],
    "age": [25, 30, 28, 35, 27, 32, 29],
}
df = pd.DataFrame(Employee_Data)
print(df.dtypes)

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

In this code, we’ve created a dataset in Pandas where the weight of the employees is represented as a list of strings. After the conversion using to_numeric(), the ‘weight‘ column is converted to float type (float32), as indicated by the output dtype: float32.

READ:  How to Create a List in Python [+5 Examples]

Output:

name      object
salary     int64
weight    object
age        int64
dtype: object
name       object
salary      int64
weight    float32
age         int64
dtype: object

Attached is a merged image displaying the Python code and its output in Visual Studio.

Convert Python string to double

Convert string to float in Python using the ast.literal_eval()

The literal_eval() function is a part of the ast module in Python. It ensures that only basic expressions are evaluated, keeping things secure while providing a quick way to turn strings into their original datatype.

For instance:

import ast

original_string = "2.71828"
double_num = ast.literal_eval(original_string)
print("String:", original_string , type(original_string))
print("Double:", double_num, type(double_num))

Output

String: 2.71828 <class 'str'>
Double: 2.71828 <class 'float'>

Shown below is a combined screenshot of the Python script and its output in Visual Studio

Convert String to Double in Python

Converting string to double in Python using the numpy.float64() function

The float64() method in Python is used to convert the input to a 64-bit floating-point number. It’s a function provided by the NumPy library for handling numerical operations efficiently.

Here’s a straightforward illustration:

import numpy as np

str = "5.9874"
converted = np.float64(str)

print("String:", str, type(str))
print("Double:", converted, type(converted))

Output:

String: 5.9874 <class 'str'>
Double: 5.9874 <class 'numpy.float64'>

Attached is a visual representation of the Python code along with its output within Visual Studio.

Convert String to Float in Python

Python is – convert string to double using np.fromstring() method

The np.fromstring() function in Python interprets a string as a 1-dimensional array and returns the array with the specified data type (type).

The sep parameter is used to specify the delimiter separating the numbers in the string.

Here’s an example to illustrate:

import numpy as np

str = '2541.8745'
converting = np.fromstring(str, dtype=float, sep=' ')
myfloat = converting[0] if len(converting) > 0 else None

if myfloat is not None:
    print(f"Converted Double: {myfloat} {type(myfloat)}")
else:
    print("Could not convert the str to a double.")

Output

Converted Double: 2541.8745 <class 'numpy.float64'>

Here’s a combined view of the Python script and its output within Visual Studio

Converting string to double in Python

String to double conversion in Python using astype.py

The astype() is a method in NumPy Python that allows us to change the data type of elements within a NumPy array, converting them from one type to another.

READ:  Add two numbers in Python using the function

Let’s see an instance:

import numpy as np
str = np.array(['68.9', '72.3', '67.8'])
float_value = str.astype(float)
print(float_value , type(float_value[0]))

We import NumPy as np, create a NumPy array str containing strings representing numbers in Python, and then apply the style (float) method to convert the strings to floating-point numbers.

Finally, it prints the converted array float_value along with the type of its first element.

Output:

[68.9 72.3 67.8] <class 'numpy.float64'>

Provided here is a consolidated view of the Python code and its output within Visual Studio

string to double conversion in Python

Conclusion

Here, we’ve explored 7 methods to convert a string to a double in Python. Each method offers advantages and uses cases, catering to different scenarios and preferences.

We have used built-in functions like float(), Decimal.decimal() method, pandas.to_numeric(), ast.literal_eval(), numpy.float64(), np.fromstring() and using astype for efficiently managing string-to-double conversions.

You may also like to read these articles: