我想知道是否必须将discount_value
转换为小数(以确保)。看来,当我使用print
discount_value对其进行测试时,它的类型会自动检测为十进制。但是,我以前有过一些案例,在该案例中,它被检测为浮动对象,并且不再起作用。
def calculate_discounted_value(self, ticket_price_gross):
[...]
elif self.percentage:
discount_value = Decimal(ticket_price_gross * self.percentage)
discount_value = quantize(discount_value, '1')
print(ticket_price_gross - discount_value, "PERCENTAGE")
def quantize(amount, decimals):
"""
Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and
2.2 do not have exact representations in binary floating point. End users
typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it
does with binary floating point. With this function we get better control about
rounding.
Therefore: amount should be come in as decimal.
"""
#amount_as_decimal = Decimal(amount)
amount_as_decimal = amount
quantized_amount = amount_as_decimal.quantize(
Decimal(decimals),
rounding=ROUND_HALF_UP
)
return quantized_amount
答案 0 :(得分:0)
由于discount_value
转换为Decimal()
,因此在将quantize()
转换为quantize
之前似乎没有必要将Decimal()
设为quantize()
。出于同样的原因,注释行似乎不必要,但是整个def calculate_discounted_value(self, ticket_price_gross):
[...]
elif self.percentage:
discount_value = Decimal(ticket_price_gross * self.percentage).quantize(Decimal(1), rounding='ROUND_HALF_UP')
print(ticket_price_gross - discount_value, "PERCENTAGE")
函数也是如此。为什么不这样做呢?
quantize()
还要注意&
的{{3}}:
与其他运算不同,如果后的系数长度 量化操作将大于精度,然后 发出InvalidOperation信号。这样可以保证,除非存在 错误条件下,量化指数始终等于 右手操作数。