I am reading a text file with floating point numbers, all with either 1 or 2 decimal points. I am using float() to convert a line into a float, and raising a ValueError if that fails. I am storing all floats in a list. When printing it out, I'd like to print it out as a 2 decimal places floating point.
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) returns -3.65. In Python 3 however, float(-3.65) returns-3.6499999999999999` which loses its precision.
I want to print the list of floats, [-3.6499999999999999, 9.1699999999999999, 1.0] with 2 decimal points only. Doing something along the lines of '%.1f' % round(n, 1) would return a string. How can I return a list of all two decimal points of floats, and not strings? So far, I rounded it using [round(num, 2) for num in list] but would need to set the decimal points / precision instead of round().
float(-3.65)is-3.6499999999999999too.. This is normal.floatis by it's very nature not 100 precise. - Martijn Pieters♦Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) │ [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin │ Type "help", "copyright", "credits" or "license" for more information. │ >>> float(-3.65) │ -3.65- darkskyfloatis not precise and I know the reasoning behind this. I'm looking an answer that will show how to print it out in 2 decimal points in Python 3. Thanks - darkskyDecimalclass in thedecimalmodule. - martineau