.quantize() 的小数舍入不使用原始上下文
Decimal rounding with .quantize() does not use original context
如果我执行以下操作,我希望 0.005
向上舍入为 0.01
而不是向下舍入为 0.00
,因为舍入设置为 ROUND_HALF_UP.
>>> import decimal
>>> currency = decimal.Context(rounding=decimal.ROUND_HALF_UP)
>>> cents = decimal.Decimal('0.00')
>>> amount = currency.create_decimal('0.005')
>>> amount
Decimal('0.005')
>>> amount.quantize(cents)
Decimal('0.00')
但是如果我将 currency 传递给 quantize()
,它会正确舍入:
>>> amount.quantize(cents, context=currency)
Decimal('0.01')
为什么 amount(从 currency 上下文创建)不使用 currency[=34 舍入=]上下文?
注意:这个问题不是问如何四舍五入到小数点后两位。我只是以此为例。我想知道 为什么 从 Context
创建的 Decimal
在 quantizing/rounding.[=19 时不使用相同的 Context
=]
您需要使用 decimal.setcontext()
设置上下文或将其作为关键字参数传递给 quantize()
函数才能正常工作。
>>> import decimal
>>> currency = decimal.Context(rounding=decimal.ROUND_HALF_UP)
>>> decimal.setcontext(currency) # setting the context
>>> cents = decimal.Decimal('0.00')
>>> amount = currency.create_decimal('0.005')
>>> amount.quantize(cents)
Decimal('0.01')
使用 decimal.getcontext().rounding = decimal.ROUND_HALF_UP
全局设置上下文也可以正常工作,但是它将用于任何 Decimal
.
的所有未来操作
>>> import decimal
>>> decimal.getcontext().rounding = decimal.ROUND_HALF_UP
>>> cents = decimal.Decimal('0.00')
>>> amount = decimal.Decimal('0.005')
>>> amount.quantize(cents)
Decimal('0.01')
小数对象不保留创建它们的上下文。使用特定上下文的小数操作,例如带有上下文参数的 Context.create_decimal
或 Decimal.quantize
,只会覆盖该操作的全局上下文;对生成的 Decimal 的进一步操作是在全局上下文中完成的。
如果你想让所有操作都使用ROUND_HALF_UP
,你可以设置全局上下文:
decimal.setcontext(currency)
但如果您想混合上下文,则必须为每个需要全局上下文以外的上下文的操作显式提供上下文。
如果我执行以下操作,我希望 0.005
向上舍入为 0.01
而不是向下舍入为 0.00
,因为舍入设置为 ROUND_HALF_UP.
>>> import decimal
>>> currency = decimal.Context(rounding=decimal.ROUND_HALF_UP)
>>> cents = decimal.Decimal('0.00')
>>> amount = currency.create_decimal('0.005')
>>> amount
Decimal('0.005')
>>> amount.quantize(cents)
Decimal('0.00')
但是如果我将 currency 传递给 quantize()
,它会正确舍入:
>>> amount.quantize(cents, context=currency)
Decimal('0.01')
为什么 amount(从 currency 上下文创建)不使用 currency[=34 舍入=]上下文?
注意:这个问题不是问如何四舍五入到小数点后两位。我只是以此为例。我想知道 为什么 从 Context
创建的 Decimal
在 quantizing/rounding.[=19 时不使用相同的 Context
=]
您需要使用 decimal.setcontext()
设置上下文或将其作为关键字参数传递给 quantize()
函数才能正常工作。
>>> import decimal
>>> currency = decimal.Context(rounding=decimal.ROUND_HALF_UP)
>>> decimal.setcontext(currency) # setting the context
>>> cents = decimal.Decimal('0.00')
>>> amount = currency.create_decimal('0.005')
>>> amount.quantize(cents)
Decimal('0.01')
使用 decimal.getcontext().rounding = decimal.ROUND_HALF_UP
全局设置上下文也可以正常工作,但是它将用于任何 Decimal
.
>>> import decimal
>>> decimal.getcontext().rounding = decimal.ROUND_HALF_UP
>>> cents = decimal.Decimal('0.00')
>>> amount = decimal.Decimal('0.005')
>>> amount.quantize(cents)
Decimal('0.01')
小数对象不保留创建它们的上下文。使用特定上下文的小数操作,例如带有上下文参数的 Context.create_decimal
或 Decimal.quantize
,只会覆盖该操作的全局上下文;对生成的 Decimal 的进一步操作是在全局上下文中完成的。
如果你想让所有操作都使用ROUND_HALF_UP
,你可以设置全局上下文:
decimal.setcontext(currency)
但如果您想混合上下文,则必须为每个需要全局上下文以外的上下文的操作显式提供上下文。