简体   繁体   中英

Formatting a 2D list of floats to 2 decimal points; Python

First off, I know a similar question has been asked before but I think the situation called for a different method of approach than mine does.

I have a list of temperatures that I just need to print out with 2 decimals. So far I have:

def getWeekAverages():
    weekAverages = []
    MAX = WEEKS
    total = 0
    for week in range (WEEKS):
        total = 0        
        for day in range(len(DAYS)):
            total += round(float(database[week][day]), 2)

        weekAverages.append(total/7)

    return weekAverages

I've tried about 10 different ways to do this, including sing "%.2f" and round. I am not very familiar with numpy arrays so I may just have to read more into that. When i run the program nothing has changed and my output comes to:

The average temperatures for a given week are   [77.71428571428571, 71.71428571428571, 74.0, 77.85714285714286, 35.42857142857143, 0.0]

I appreciate anyone's time they provide.

You are using int() to parse a string representation of a floating-point number. You should do that with float() .

total += float(database[week][day])

If you want to turn that into an integer, you can either round it (Python 3's round() returns an int when rounding to zero decimal places) or use the int() function on that float (it can't handle strings that represent floating-point numbers, but it can find the floor of a floating-point number).

total = int(total)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM