python如何四舍五入到小数点后两位?

How to round to two decimal places in python?

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

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)`

您放错了 %.2:

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

而且你不需要 %.

round(number[, ndigits])

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise, the return value has the same type as number.

关于金额,不应该使用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