蟒蛇小数-舍入到最接近的整数(无美分)-用ROUND_HALF_UP [英] python decimals - rounding to nearest whole dollar (no cents) - with ROUND_HALF_UP

查看:129
本文介绍了蟒蛇小数-舍入到最接近的整数(无美分)-用ROUND_HALF_UP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Decimal.quantize()实现以下目的:-

I'm trying to use Decimal.quantize() to achieve the following: -

对于任何金额(以默认精度的python十进制表示),我想使用 decimal.ROUND_HALF_UP 对其进行四舍五入,以便在四舍五入后不加分。

For any amount of money, expressed as a python decimal of default precision, I want to round it using decimal.ROUND_HALF_UP so that it has no cents after rounding.

例如,给定1.25,我试图获得1.00(不表示任何美分)

For example, given 1.25, I'm trying to obtain 1.00 (signifying no cents)

给出1.49,我试图获得1.00

given 1.49 I'm trying to obtain 1.00

给出1.50我试图获得2.00

given 1.50 I'm trying to obtain 2.00

给出1.87我试图获得2.00

given 1.87 I'm trying to obtain 2.00

给定2.00我正在尝试获得2.00

given 2.00 I'm trying to obtain 2.00

因此,美分有两个范围-0美分至49美分; 50美分到99美分。我想四舍五入到49美分,我想四舍五入到50美分。我正在尝试使用两个有效的小数位(始终为00)获得结果。

So there are two ranges for the cents -- 0 cent to 49 cents; and 50 cents to 99 cents. For cents upto 49, I want to round down, for cents 50 and up I want to round up. I'm trying to obtain the result with two significant decimal places (which will always be 00).

我这里没有负值要处理。我如何舍入我的美元以获得我想要的金额?除了 quantize 以外,还有其他选择吗?

I don't have any negative values to deal with here. How do I round my dollars to get the amount I want? Also is there any other option other than quantize?

推荐答案

I' d请尝试以下操作:

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')

这里的关键部分是第一次调用: x.quantize(Decimal('1'),rounding = ROUND_HALF_UP)使用给定的舍入模式将 x 舍入到最接近的整数。第一个参数( Decimal('1'))确定四舍五入结果的指数,因此,如果将其替换为例如 Decimal('0.1')会四舍五入到最接近的十分之一,如果您将其替换为 Decimal('1e1')会四舍五入到 10 的最接近倍数。

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.

然后第二个 quantize 调用只是将多余的两个小数位放回去,这样您就可以得到 Decimal('2.00')而不是仅 Decimal(2)

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).

您也可以使用 to_integral_value 方法代替如果需要,可以进行第一个量化调用:

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.

这篇关于蟒蛇小数-舍入到最接近的整数(无美分)-用ROUND_HALF_UP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆