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

PythonStringDouble

Python Problem Overview


I would like to know how to convert a string containing digits to a double.

Python Solutions


Solution 1 - Python

>>> x = "2342.34"
>>> float(x)
2342.3400000000001

There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).

Solution 2 - Python

The decimal operator might be more in line with what you are looking for:

>>> from decimal import Decimal
>>> x = "234243.434"
>>> print Decimal(x)
234243.434

Solution 3 - Python

Be aware that if your string number contains more than 15 significant digits float(s) will round it.In those cases it is better to use Decimal

Here is an explanation and some code samples: https://docs.python.org/3/library/sys.html#sys.float_info

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser46646View Question on Stackoverflow
Solution 1 - PythonMongooseView Answer on Stackoverflow
Solution 2 - PythonfoomipView Answer on Stackoverflow
Solution 3 - Pythonuser1767754View Answer on Stackoverflow