Skip to content
Advertisement

How to round each item in a list of floats to 2 decimal places?

I have a list which consists of float values but they’re too detailed to proceed. I know we can shorten them by using the ("%.f" % variable) operator, like:

JavaScript

My question is how can I turn a list of values into their rounded equivalents without using an iterator. I’ve tried something, but it throws a TypeError:

JavaScript

How can I provide a clean list like:

JavaScript

Advertisement

Answer

"%.2f" does not return a clean float. It returns a string representing this float with two decimals.

JavaScript

returns:

JavaScript

Also, don’t call your variable list. This is a reserved word for list creation. Use some other name, for example my_list.

If you want to obtain [0.30, 0.5, 0.20] (or at least the floats that are the closest possible), you can try this:

JavaScript

returns:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement