darksky - 3 months ago 14x

Python Question

I am reading a text file with floating point numbers, all with either 1 or 2 decimal points. I am using

`float()`

`ValueError`

Assume I have a text file with the numbers -3,65, 9,17, 1. I read each one, and once I convert them to float and append them to a list. Now in Python 2, calling

`float(-3.65)`

`-3.65`

`float(-3.65) returns`

I want to print the list of floats,

`[-3.6499999999999999, 9.1699999999999999, 1.0]`

`'%.1f' % round(n, 1)`

`[round(num, 2) for num in list]`

`round()`

Answer

In a word, you can't.

`3.65`

cannot be represented exactly as a `float`

. The number that you're getting is the nearest number to `3.65`

that has an exact `float`

representation.

The difference between (older?) Python 2 and 3 is purely due to the default formatting.

I am seeing the following both in Python 2.7.3 and 3.3.0:

```
In [1]: 3.65
Out[1]: 3.65
In [2]: '%.20f' % 3.65
Out[2]: '3.64999999999999991118'
```

For an exact decimal datatype, see `decimal.Decimal`

.

Source (Stackoverflow)

Comments