【发布时间】:2013-12-31 11:08:55
【问题描述】:
我正在尝试将数字的输出限制为 4 个字符(包括小数)。
def costEdit(nCost):
nCost = '%.2f'%(nCost*1.25)
nCost = nCost * 1.25
return nCost
我希望将 nCost 截断到小数点后 2 位。例如。如果 nCost 是 8.364912734,则将其切断为 8.36 并编辑 nCost 变量以替换为该变量。有什么想法吗?
我得到了错误:
Traceback (most recent call last):
File "C:\Python33\My Codes\TextTowns\TextTowns.py", line 59, in <module>
costEdit(nCost)
File "C:\Python33\My Codes\TextTowns\TextTowns.py", line 27, in costEdit
nCost = nCost*1.25
TypeError: can't multiply sequence by non-int of type 'float'
我将其用作:costEdit(nCost)
【问题讨论】:
-
术语挑剔:如果 nCost 等于
8.364912734,它不是整数。整数是整数。 -
我的错,谢谢:P
-
这是附注。如果你得到一个大于 9.99 的数字,你会遇到 5+ 个字符。限制为 2 个小数位还是只有 4 个字符更重要?你宁愿有
1000而不是1000.01吗? -
你希望这个函数返回一个四舍五入的字符串表示形式,还是一个实际的四舍五入数字?
-
这不是 python limiting floats to two decimal points 的副本。这个问题是关于
13.95没有精确表示为float的事实,并且 Python 2.5 和更早的repr-d 以不直观的方式使用此类值。