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

569,196

Solution 1

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

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

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

Share:
569,196

Related videos on Youtube

user46646
Author by

user46646

Updated on June 18, 2020

Comments

  • user46646
    user46646 almost 4 years

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

    • Admin
      Admin about 14 years
      That is not a python double. A python double has unlimited capacity.
  • habnabit
    habnabit over 15 years
    Or, more specifically, Python floats are C doubles.
  • Evorlor
    Evorlor over 10 years
    Bah used float instead of double. now my code is off by .0000000001 which hurts
  • drevicko
    drevicko over 10 years
    incidentally, this also works with exponent notation. eg: float('7.5606e-08') produces the expected python float.
  • Bruce_Warrior
    Bruce_Warrior over 8 years
    With 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
  • user1510539
    user1510539 over 6 years
    Use >>> 0.1 + 0.2 for double. >>> 0.1 + 0.6 for float.
  • mendel
    mendel over 2 years
    The returned thing is a Decimal(...), not a simple number.