How to round a Python Decimal to 2 decimal places?

2019-08-20 04:56发布

问题:

I've got a python Decimal (a currency amount) which I want to round to two decimal places. I tried doing this using the regular round() function. Unfortunately, this returns a float, which makes it unreliable to continue with:

>>> from decimal import Decimal
>>> a = Decimal('1.23456789')
>>> type(round(a, 2))
<type 'float'>

in the decimal module, I see a couple things in relation to rounding:

  • ROUND_05UP
  • ROUND_CEILING
  • ROUND_DOWN
  • ROUND_FLOOR
  • ROUND_HALF_DOWN
  • ROUND_HALF_EVEN
  • ROUND_HALF_UP
  • ROUND_UP
  • Rounded

I think that none of these actually give what I want though (or am I wrong here?).

So my question: does anybody know how I can reliably round a Python Decimal to 2 decimal places so that I have a Decimal to continue with? All tips are welcome!

回答1:

You could use the quantize() method:

>>> import decimal
>>> decimal.getcontext().prec = 20
>>> a = decimal.Decimal(321.12345)
>>> a
Decimal('321.12344999999999117790139280259609222412109375')
>>> TWO_PLACES = decimal.Decimal("0.01")
>>> a.quantize(TWO_PLACES)
Decimal('321.12')


回答2:

If you are using Jupyter Notebook, just add the magic function %precision 2 for 2 decimal and so forth.

But if your values are not float() type then you might use the following:

 from decimal import getcontext, Decimal
 getcontext().prec = 2
 # for example, take integer value
 mynum = 2
 type(mynum) # Int
 print round(Decimal(mynum), 2) # 10.0


回答3:

This has came to my mind:

Decimal(str(round(a, 2)))

but I don't know how fast it is.



回答4:

The first one you tried worked just fine for me.

import decimal

type(round(decimal.Decimal('1.23456789'),2))

<class 'decimal.Decimal'>