Boosted_d16 Boosted_d16 - 2 months ago 7
Python Question

Convert a list of string floats to a list of floats with 2 decimal points

Did my research and made several improvements, got very close to solving this issue but now I'm stuck and need help please.

Task: To convert a list of strings floats to floats with 2 decimal points

Original list:

mylist = ['17.21', '33.40', '24.39', '3.48', '1.02', '0.61', '18.03', '1.84']


Aim

mylist = [17.21, 33.40, 24.39, 3.48, 1.02, 0.61, 18.03, 1.84]


My script attempts

mylisttwo = map(float, mylist)


It gave me this

[17.21, 33.4, 24.39, 3.48, 1.02, 0.60999999999999999, 18.03, 1.84]


Then I thought id format it

floatlist = []
for item in mylisttwo:
floatlist.append("{0:.2f}".format(item))


but that gave me a list of string floats again!! arghhhh

['17.21', '33.40', '24.39', '3.48', '1.02', '0.61', '18.03', '1.84']


What am I doing wrong here?

Thanks

Answer

[round(float(i), 2) for i in mylist]

This should work. Format is for inserting strings in other strings, as in "Hello, {}! What is your favourite {}?".format("Jim", "colour").

If you want to the numbers to only exist to 2 decimal places, you could use the decimal module.

Comments