I would like to know how to convert a string containing digits to a double.
Asked
Active
Viewed 6.1e+01k times
3 Answers
391
>>> 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).
-
51
-
1Bah used float instead of double. now my code is off by .0000000001 which hurts – Evorlor Jan 18 '14 at 19:24
-
2incidentally, this also works with exponent notation. eg: `float('7.5606e-08')` produces the expected python float. – drevicko Feb 13 '14 at 07:33
-
2With my python (version 2.7.10), when I assign `>>> x = "2342.34"` and convert to float `>>> float(x) ` I get `2342.34` instead the `2342.3400000000001` reported by @Mongoose – Bruce_Warrior Aug 31 '15 at 20:21
-
57
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

foomip
- 1,395
- 11
- 4
5
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

user1767754
- 23,311
- 18
- 141
- 164