Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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:

result = [359.70000000000005] result = "%.2f" % result result = [359.70] 

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:

list = [0.30000000000000004, 0.5, 0.20000000000000001] list = "%.2f" % list TypeError: not all arguments converted during string formatting 

How can I provide a clean list like:

list = [0.30, 0.5, 0.20] 
like image 362
Fish Avatar asked Mar 16 '11 13:03

Fish


People also ask

How do you write a float value up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you round something to 2 decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.


2 Answers

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

my_list = [0.30000000000000004, 0.5, 0.20000000000000001] my_formatted_list = [ '%.2f' % elem for elem in my_list ] 

returns:

['0.30', '0.50', '0.20'] 

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:

my_rounded_list = [ round(elem, 2) for elem in my_list ] 

returns:

[0.29999999999999999, 0.5, 0.20000000000000001] 
like image 181
eumiro Avatar answered Sep 20 '22 17:09

eumiro


If you really want an iterator-free solution, you can use numpy and its array round function.

import numpy as np myList = list(np.around(np.array(myList),2)) 
like image 37
john ktejik Avatar answered Sep 20 '22 17:09

john ktejik