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()
.