Reading a float from string

floating-point, python, string

Solution

Direct answer: You can't. Floats are imprecise, by design. While python's floats have more than enough precision to represent 1.0000, they will never represent a "1-point-zero-zero-zero-zero". Chances are, this is as good as you need. You can always use string formatting, if you need to display four decimal digits.

print '%.3f' % float(1.0000)

Indirect answer: Use the `decimal` module.

from decimal import Decimal
d = Decimal('1.0000')

The `decimal` package is designed to handle all these issues with arbitrary precision. A decimal "1.0000" is exactly 1.0000, no more, no less. Note, however, that complications with rounding means you can't convert from a `float` directly to a `Decimal`; you have to pass a string (or an integer) to the constructor.

Problem

I have a simple string that I want to read into a float without losing any visible information as illustrated below: ``` s = ' 1.0000\n' ``` When I do `f = float(s)`, I get `f=1.0` How to trick this to get `f=1.0000` ? Thank you

Original source

Related problems