Search code examples
python-3.xroundingbuilt-in

why round() builtin function in python3 is not working for me?


for a given student we need to calculate average marks. Input will be like this:

3

Krishna 67 68 69

Arjun 70 98 63

Malika 52 56 60

Malika

code:

if __name__ == '__main__':
n = int(input()) # takes input
student_marks = {} 
for _ in range(n):
    name, *line = input().split()
    scores = list(map(float, line))
    student_marks[name] = scores
query_name = input()

a,b,c=student_marks[query_name]
avg=(a+b+c)/3   #avg is calculated.
output =round(avg,2) ## why can't I use print(round(avg,2)) to give 56.00 but it is giving 56.0 only
print("%.2f" % output) # for my output in two decimal places I had to use this

Solution

  • In order to get what you expected ,use format function instead of round function.

    >>> num=3.65
    >>> "The number is {:.2f}".format(num)
    'The number is 3.65'
    

    or equivalently with f-strings (Python 3.6+):

    >>> num = 3.65
    >>> f"The number is {num:.2f}"
    'The number is 3.65'
    

    As always, the float value is an approximation:

    >>> "{}".format(f)
    '3.65'
    >>> "{:.10f}".format(f)
    '3.6500000000'
    >>> "{:.20f}".format(f)
    '3.64999999999999991118'
    

    For 56

    >>> num=56
    >>> "The number is {:.2f}".format(num)
    'The number is 56.00'