【问题标题】:How to round to two decimal places in python? [duplicate]如何在python中四舍五入到小数点后两位? [复制]
【发布时间】:2022-01-16 12:58:13
【问题描述】:

我正在尝试在 python 中为硬件计算账单。无法弄清楚如何将数字四舍五入到小数点后两位。这是我到目前为止所拥有的。每次我尝试圆形功能时,它都不起作用并给我一条错误消息。救命?!

ss_cost = 3.95 * 2
hb_cost = 8.95 * 2
ds_cost = 2.50 * 2
subtotal = (ss_cost) + (hb_cost) + (ds_cost)
tax = (round(subtotal * 0.0475), %.2)
print (tax)`

【问题讨论】:

  • round, (round(subtotal * 0.0475), %.2) 改为round(subtotal * 0.0475, 2)
  • 金额方面,不要用round,应该用decimal
  • 当您在 Google 上搜索您的问题标题时,标记的副本会出现作为第一个结果。下一次,在你问之前做一些基础研究

标签: python rounding


【解决方案1】:

你放错了%.2

tax = (round(subtotal * 0.0475, 2))

你不需要%.

【讨论】:

  • 你也不需要额外的括号。
【解决方案2】:

round(number[, ndigits])

返回小数点后四舍五入到 ndigits 精度的数字。如果 ndigits 被省略或为 None,则返回与其输入最接近的整数。

对于支持 round() 的内置类型,值被四舍五入到最接近 10 的幂减去 ndigits 的倍数;如果两个倍数相等,则向偶数选择进行舍入(例如,round(0.5) 和 round(-0.5) 均为 0,round(1.5) 为 2)。任何整数值都对 ndigits 有效(正数、零或负数)。如果省略 ndigits 或 None,则返回值为整数。否则,返回值的类型与数字相同。

涉及金额时,不要使用round,最好使用decimal

from decimal import Decimal


ss_cost = 3.95 * 2
hb_cost = 8.95 * 2
ds_cost = 2.50 * 2
subtotal = (ss_cost) + (hb_cost) + (ds_cost)
tax = Decimal(subtotal * 0.0475).quantize(Decimal("0.00"))
print (tax)

# 1.46

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-26
    • 2013-12-25
    • 1970-01-01
    • 2017-03-26
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多