ID : 101

viewed : 222

Tags : PythonPython StringPython Double

90

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.

`float()`

FunctionThe `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 `

`decimal.Decimal()`

MethodThe `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 `