Reputation: 49
a=0.005
print ('%.2f'%a)
b=90.005
print('%.2f'%b)
c=90.015
print('%.2f'%c)
Above code is written in python3 and the output is following:
0.01
90.00
90.02
Is this any kind of computational error or m missing a point?
Upvotes: 0
Views: 214
Reputation: 2821
I think the problem here is the second one, which is
b = 90.005
print('%.2f' % b)
Now as @divibisan said, if the digit is between 0-4, it's rounded down, if it's between 5-9, it's rounded up. So why is 90.005
not rounded up ?
Because computers can not represent the floating points precisely. If you look at it closely you will see that 90.005
is represented as,
>>> print('%.50f' % b)
90.00499999999999545252649113535881042480468750000000
That's the reason it is being rounded down, while others behave normally.
>>> print ('%.50f'%a)
0.00500000000000000010408340855860842566471546888351
# 0.01
>>> print ('%.50f'%c)
90.01500000000000056843418860808014869689941406250000
# 90.02
Upvotes: 2