0
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?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
  • @mhd That doesn't explain why the first and last are rounded – OneCricketeer Jun 01 '18 at 13:36
  • 1
    If I'd to guess, it's somewhat related to this https://stackoverflow.com/questions/588004/is-floating-point-math-broken – OneCricketeer Jun 01 '18 at 13:38
  • 1
    I think this explains it: https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior – sjw Jun 01 '18 at 13:41
  • 5
    Possible duplicate of [Python 3.x rounding behavior](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) – divibisan Jun 01 '18 at 13:48
  • @thesilkworm that question answers my problem properly. Looking for a better answer – Shivendra Saxena Jun 01 '18 at 13:48
  • What's your question? When you round a number to 2 digits, if the 3rd digit is 0-4 it is rounded down while if the 3rd digit is 5-9 it is rounded up. Your example is exactly what is expected when rounding numbers. Are you trying to do something different? – divibisan Jun 01 '18 at 13:50
  • @divisbisan I think u hadn't observed my question properly – Shivendra Saxena Jun 01 '18 at 13:52

1 Answers1

2

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
BcK
  • 2,548
  • 1
  • 13
  • 27