Django+Python:会自动检测到类型吗?

2024-05-13 22:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否必须将discount_value转换成十进制(以确保)。似乎当我用print折扣值测试它时,它的类型被自动检测为十进制。然而,我以前有过这样的情况,它被检测为一个浮动,不再工作了。你知道吗

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

Tags: selfvaluedefasdiscountticketamountprice
1条回答
网友
1楼 · 发布于 2024-05-13 22:21:16

似乎没有必要在将discount_value传递给quantize()之前生成Decimal(),因为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")

另外请注意this关于quantize()

Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision, then an InvalidOperation is signaled. This guarantees that, unless there is an error condition, the quantized exponent is always equal to that of the right-hand operand.

相关问题 更多 >