Convert String to Double in Python

  1. Convert a String to a Double in Python Using the float() Function
  2. Convert a String to a Double in Python Using the decimal.Decimal() Method

In this tutorial, we will talk about the various ways to convert a string to a numeric variable with the precision equivalent to double type in Python. Unlike other programming languages like C, C++, and Java, Python does not have any double type variable. But the float type in Python has the same precision as double in other programming languages.

We can also convert a number or floating-point number stored as a string to a Python decimal type. The decimal type can have as much precision as needed for a problem and store exact numeric values, unlike the float type. The float type stores the numeric value as binary and can not exactly represent numeric values that do not have an exact representation in the binary system like 3.3 or 3.14 etc.

Convert a String to a Double in Python Using the float() Function

The float() function accepts a number or a string as input and returns the floating-point number or a float type as output.

To convert a string into a float, we can pass the string to the float() function. The example code below demonstrates how to convert a string to a float (double-precision number) using the float() method.

string = '1974.6323'
myfloat = float(string)
print(myfloat)

Output:

1974.6323

Convert a String to a Double in Python Using the decimal.Decimal() Method

The decimal.Decimal() constructor method of the decimal module takes a numeric value as input and converts it into a decimal type, which can exactly store and represent all the numeric values and can have as much precision as needed.

We can pass the string which we need to convert into a double-precision number to the Decimal() method and get a decimal type variable. The code example below demonstrates how to use the Decimal() method to convert a string to a double-precision number in Python.

from decimal import Decimal

string = '1974.6323'
myfloat = Decimal(string)
print(myfloat)

Output:

1974.6323
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python String

  • Convert String to Datetime in Python
  • Remove Substring From String in Python
  • Related Article - Python Double

  • Split String to Char Array in Python
  • Capitalize First Letter of Each Word in Python