python - Django + Python:会自动检测类型吗?
问题描述
我想知道我是否必须转换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
解决方案
在将它传递给之前似乎没有必要做discount_value
a因为转换为. 出于同样的原因,注释行似乎是不必要的,但您的整个函数也是如此。为什么不这样做呢?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()
与其他操作不同,如果量化操作后的系数长度大于精度,则会发出 InvalidOperation 信号。这保证了,除非存在错误条件,否则量化的指数总是等于右手操作数的指数。
推荐阅读
- python-3.x - 通过python启动shell命令
- php - 如何发送将视图转换为pdf的电子邮件,然后将其附加到laravel的邮件中
- javascript - 记忆匹配纸牌游戏
- oracle - 如果我们有任何 truncate 或 delete 语句 - 当我们在 toad 或 SQL 开发人员中运行脚本时,如何获得弹出窗口
- ruby-on-rails - 单击幻灯片时,Bootstrap Carousal 消失
- node.js - Appllo GraphQL 为第三级子级返回 null
- python - 如何计算特定区域内的物体数量?
- angular - 是否可以在构建时获取 Angular Dart 应用程序的 Web 资源?
- c# - 如何停止现有的 URL 没有在浏览器中打开不同的选项卡?
- html - CSS :before 元素与我的文本不对齐