首页 > 解决方案 > 你如何乘以保持相同小数位的小数

问题描述

星期三 Woahs - 尝试使用小数学习“简单”算术

>>> a = Decimal('100.00')
>>> a
Decimal('100.00')
>>> b = Decimal('4.00')
>>> b
Decimal('4.00')
>>> a + b
Decimal('104.00')
>>> a * b
Decimal('400.0000')

如何将 Decimals 与 2 个 decimal_places 相乘以保持/舍入/限制为 2 个位置?( 4.00 * 100.00=> 400.0000[即 4 个小数位而不是 2 个])

我正在尝试计算金钱、税收、小计、项目等……只是一些基本的会计算术。以下是一些输入和预期输出:

4.00 * 100.00 => 400.00
0.01 * 0.01 => 0.00
1.00 * 0.07 => 0.07
1.00 * 0.075 => 0.08 (im not sure I may have a use case for that, but Im sure it could be chained/curried to get that [ie `a = 7.50 / 100` then `100.00 * a` => `0.08`])

我不确定这是否称为精度误差、蠕变或什么……。

标签: pythonpython-3.x

解决方案


您可以使用 设置 Decimal 的小数位quantize()

例如

>>> d = Decimal(123.456789)
>>> d.quantize(Decimal('0.01'))
Decimal('123.46')

例如在你的情况下,你可以做

c = (a*b).quantize(Decimal('0.01'))
# or 
c = (a*b).quantize(a)    # c will be in same exponent as a
# or, depending your preference in style
c = getcontext().quantize( a*b, Decimal('0.01'))

推荐阅读