Phong Vy
Phong Vy

Reputation: 401

Wrong result on rounding method with 2 decimal places

I got confusing with the result of round() with 2 decimal places

a = 1352.845
res = round(a, 2)
=> 1352.85 (Right as I expected)

b = 578.005
res = round(b, 2)
=> 578.0 (Wrong, It would be 578.01 instead of 578.0)

what happens with case b or Have I misunderstood anything?

Answer:

from decimal import Decimal, ROUND_UP

Decimal('578.005').quantize(Decimal('.01'), rounding=ROUND_UP)

Because it needs to be used for monetary so the default convention of python round() (Banker's Rounding) doesn't right in my case

Upvotes: 1

Views: 424

Answers (3)

ycx
ycx

Reputation: 3211

It is not wrong actually.
It is Banker's Rounding and is an implementation detail on purpose.

If you wish to retain the 'always round 0.5 up' method, you can do so by doing:

import decimal
#The rounding you are looking for
decimal.Decimal('3.5').quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP)
>>> Decimal('4')
decimal.Decimal('2.5').quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP)
>>> Decimal('3')


#Other kinds of rounding
decimal.Decimal('2.5').quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_EVEN)
>>> Decimal('2')

decimal.Decimal('3.5').quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_DOWN)
>>> Decimal('3')

Upvotes: 2

Wes Doyle
Wes Doyle

Reputation: 2287

While it can be confusing, this is due to the fact that most decimal fractions cannot be represented exactly as a float type.

For further reference, see: https://docs.python.org/3/tutorial/floatingpoint.html#tut-fp-issues

Upvotes: 2

Rachit Bhargava
Rachit Bhargava

Reputation: 168

Recall your Physics / Mathematics lesson where they taught how rounding off works.

If the last digit is a '5' and you round that off, it's preceding digit shall move to the next even digit if it is odd but shall remain the same if it is already even.

Upvotes: 0

Related Questions