0

I'm trying to format the follow program so that the results for 'average' are only displayed to 2 decimal places. I get that the '%.2f' % code is used to do that, but I can't figure out how to integrate it into the final line of code producing an error.

Here is the program and I'm working on.

#the user has to enter three numbers for the program to average

#request the first number
answer1 = input('Please enter the first number: ')
answer1 = int(answer1)

#request the second number
answer2 = input('Please enter the second number: ')
answer2 = int(answer2)

#request the third number
answer3 = input('Please enter the third number: ')
answer3 = int(answer3)

final = answer1 + answer2 + answer3
final = int(final)

#print the average
print('The average of these numbers is ', final / 3)

It's the final line here that I can't figure out where to insert the '%.2f' % to return the results for 2 decimal places.

Any help would be greatly appreciated.

Georgy
  • 12,464
  • 7
  • 65
  • 73
  • Possible duplicate of [Limiting floats to two decimal points](https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points) – Georgy Dec 13 '18 at 13:28

2 Answers2

0
print('The average of these numbers is %0.2f' %final / 3)
Waseem Randhawa
  • 149
  • 2
  • 17
0

You need to cast the variable final into float. For example, final as an integer would result in 10 / 3 = 3, but as a float 10.0 / 3 = 3.333333. Then you can use the function round() to round float to certain number of decimals. Example:

a = 10.0
final = round(a/3, 2)
final is now 3.33 
Thomas Richter
  • 833
  • 8
  • 20