0

I have the code finished up in fact it is entirely done but I just need help at the end of my function for it to return a rounded float.

def average_area(glacier_list):
    average=0
    Sum=0
    for row in glacier_list:
        Sum += float(row[9])
            
    average = Sum / len(glacier_list)
    return average 

def main():
   print('Average Area:, '(average_area(csv_reader(file))))

if __name__ == '__main__':
    main()

When the code runs through I get 'Average Area: 2.0335740566037788' but I need to get 'Average Area: 2.03'

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • Do you need the the number itself to be rounded (e.g., rounded is needed for future calculations) or do you just need the display to be rounded. If so, round up / down /middle? You may want to use the `decimal` module instead of floats in your program. – tdelaney Nov 18 '22 at 04:42
  • The question title says that you weren't "able to round". What do you mean you weren't able? What did you try? Did you get an error? – John Gordon Nov 18 '22 at 04:45

1 Answers1

0

You'll want to use round(average, 2) to round the average to the 2nd decimal point, and then convert it to a string and format it to only include 2 characters after the "." decimal point, and then convert it back to a float before returning it.

credit where it's due: this was a paraphrasing of the best answer on the linked question by Ken Y-N above, which was written by Rex Logan in the question.

Good luck with everything!

  • If this is your solution, then you could use `float(f"{x:.02f}")` to cast it to a string with 2 decimal places. – Shmack Nov 18 '22 at 05:01
  • Would doing so include getting the long version of the float rounded to that second decimal place, or would the poster need to do that rounding first, and then use float(f"{x:.02f}") to get it in the right configuration? – NeonSilver2 Nov 18 '22 at 05:14
  • I'm not certain I understand your question, but `f"x:.02f"` will round x to 2 decimal places, and of course `float()` will cast the string to a float. – Shmack Nov 18 '22 at 05:20
  • I'll clarify: I was wondering if the formatting would actually round that second decimal point based on whether the third decimal point was 5 or over in value, or if it just snipped off the remaining digits after 2 decimal places with no regard for what they were. I think you're saying that the formatting with the float() function /does/ round it with regards to the third decimal point, which would be ideal. – NeonSilver2 Nov 18 '22 at 05:30
  • You're right, `.02f` is precision - I don't know why I thought it was rounded. – Shmack Nov 18 '22 at 05:44