Reputation: 93
When working with the built in decimal module in python I can round decimals as follows.
Decimal(50.212345).quantize(Decimal('0.01'))
> Decimal('50.21')
But I can also round the same number with the built in round function
round(Decimal(50.212345), 2)
> Decimal('50.21')
Why would I use one instead of the other when rounding Decimals? In previous answers about rounding decimals, users suggested to use quantize because the built in round function would return a value of type float. Based on my testing, these both return a Decimal. Other than syntax, is there a reason to choose one over the other?
Upvotes: 9
Views: 2104
Reputation: 70582
The return types aren't always the same. round()
used with a single argument actually returns an int
:
>>> round(5.3)
5
>>> round(decimal.Decimal("5.3"))
5
Other than that, suit yourself. quantize()
is especially handy if you want a deoimal rounded to "the same" precision as another decimal you already have.
>>> x = decimal.Decimal("123.456")
>>> x*x
Decimal('15241.383936')
>>> (x*x).quantize(x)
Decimal('15241.384')
See? The code doing this doesn't have to know that x
originally had 3 digits after the decimal point. Just passing x
to quantize()
forces the function to round back to the same precision as the original x
, regardless of what that may be.
quantize()
is also necessary if you want to use a rounding mode other than the default nearest/even.
>>> (x*x).quantize(x, decimal.ROUND_FLOOR)
Decimal('15241.383')
Upvotes: 13