python decimals - rounding to nearest whole dollar (no cents) - with ROUND_HALF_UP

◇◆丶佛笑我妖孽 提交于 2019-12-05 20:27:50

I'd try something like the following:

>>> from decimal import Decimal, ROUND_HALF_UP
>>> x = Decimal('2.47')
>>> x.quantize(Decimal('1'), rounding=ROUND_HALF_UP).quantize(Decimal('0.01'))
Decimal('2.00')

The key part here is the first call: x.quantize(Decimal('1'), rounding=ROUND_HALF_UP) gives x rounded to the nearest integer, with the given rounding mode. The first argument (Decimal('1')) determines the exponent of the rounded result, so if you replaced it with e.g., Decimal('0.1') it would round to the nearest tenth, instead, and if you replaced it with Decimal('1e1') it would round to the nearest multiple of 10.

Then the second quantize call just puts the extra two decimal places back in so that you get Decimal('2.00') coming out instead of just Decimal(2).

You could also use the to_integral_value method in place of the first quantize call, if you want:

>>> x.to_integral_value(rounding=ROUND_HALF_UP).quantize(Decimal('0.01'))
Decimal('2.00')

I can't see any strong reason to prefer either solution over the other.

I did this:

def currenctyUSD(val):
  valint = int(val)
  if float(val) > float(valint):
    valint = valint + 1
  return '{0:.2f}'.format(float(valint));

If the original float value is greater than the float(int(val)) then the original float had some cents :) so we need to add 1.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!