How to round the value to two decimal places?

#how to round the value to two decimal places?

p=10

l=5

a=0

distance = [ ]

distance.append(0)

for n in range(0,p):

a +=(l/p)*2.9

distance.append(a)

print('distance = ',distance)

check the round function
https://docs.python.org/3/library/functions.html#round

1 Like

for the list I couldn’t get it to work

it works on numbers, not lists, so you need to use it on the numbers

Be careful with round, it has some tricky perks:

a = 2.3
print(round(a))#2
b = 2.5
print(round(b))#2
c = 2.51
print(round(c))#3

why tricky? that correctly rounds to the nearest integer, if you want to round down you need to use a different function

anyway, if you add round in the correct place you can get this output

distance =  [0, 1.45, 2.9, 4.35, 5.8, 7.25, 8.7, 10.15, 11.6, 13.05, 14.5]

Well, for me round was little confusing at first.

In school/university we were doing rounding like 2.5 >>> 3.

So I wrote the above.

I totally agree that it works as it should work, no argument here

when it’s exactly 0.5 it rounds to the even number, it’s in the specifications, it’s also how I have been taught for reducing errors on rounding

1 Like