Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我试图弄清楚如何打印格式化字符串四舍五入到有效数字。说我有:
x = 8829834.123
我想将它四舍五入打印为整数。我试过了:
print "%4d"%x
我只是得到:
8829834
为什么不显示:
8829000?
我认为这就是字符串格式化的工作方式。
四舍五入到 4 位有效数字:
f = float("%.4g" % 8829834.123)
要将其打印为整数:
print "%.0f" % f # -> 8830000
格式说明符不支持整数舍入,可能有一些解决方案但不是开箱即用的,这里有几个
>>> print "{:d}000".format(int(x/1000)) 8829000 >>> print "{:d}".format(int(round(x,-3))) 8830000