首页 > 解决方案 > Django + Python:会自动检测类型吗?

问题描述

我想知道我是否必须转换discount_value成小数(以确保)。似乎当我使用printdiscount_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

标签: python

解决方案


在将它传递给之前似乎没有必要做discount_valuea因为转换为. 出于同样的原因,注释行似乎是不必要的,但您的整个函数也是如此。为什么不这样做呢?Decimal()quantize()quantizeDecimal()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()

与其他操作不同,如果量化操作后的系数长度大于精度,则会发出 InvalidOperation 信号。这保证了,除非存在错误条件,否则量化的指数总是等于右手操作数的指数。


推荐阅读