将税率添加到 Python 中的基本价格并四舍五入到 0 或 5 美分
Adding a tax rate to a base price in Python and rounding to 0 or 5 cents
我有一个数据模型(sqlite3 数据库字段),价格是这样存储的:
base_price1 = 3715
base_price2 = 1000
实际上代表
.15
.00
我根据论坛中的几项建议(例如 https://dba.stackexchange.com/questions/15729/storing-prices-in-sqlite-what-data-type-to-use)遵循了该惯例。
现在我以相同的方式存储了税率:
tax = 2100
税收实际上在哪里
21.00%
我想计算出最终价格并四舍五入到 0 或 5 美分。
所以
.15 * 1.21 = .9515
所以要存储的最终值需要是:
4495
在 Python2.7 中实施此 pythonic/simplest 的方法是什么?
四舍五入可以使用:
def round_to_0_or_5(i):
return int((5 * round((i/5.),0)))
for i in [3445, 5550, 4442, 4443]:
print(i, "-->", round_to_0_or_5(i))
# 3445 --> 3445
# 5550 --> 5550
# 4442 --> 4440
# 4443 --> 4445
(适用于 Python 2.7 和 Python 3)
我有一个数据模型(sqlite3 数据库字段),价格是这样存储的:
base_price1 = 3715
base_price2 = 1000
实际上代表
.15
.00
我根据论坛中的几项建议(例如 https://dba.stackexchange.com/questions/15729/storing-prices-in-sqlite-what-data-type-to-use)遵循了该惯例。
现在我以相同的方式存储了税率:
tax = 2100
税收实际上在哪里
21.00%
我想计算出最终价格并四舍五入到 0 或 5 美分。
所以
.15 * 1.21 = .9515
所以要存储的最终值需要是:
4495
在 Python2.7 中实施此 pythonic/simplest 的方法是什么?
四舍五入可以使用:
def round_to_0_or_5(i):
return int((5 * round((i/5.),0)))
for i in [3445, 5550, 4442, 4443]:
print(i, "-->", round_to_0_or_5(i))
# 3445 --> 3445
# 5550 --> 5550
# 4442 --> 4440
# 4443 --> 4445
(适用于 Python 2.7 和 Python 3)