我正在使用Python 2.7,并且我拥有的代码如下:
a = 10.5 * 22.34 / 2.0
print "%.2f" % a
我预期的结果是117.29,但显示为117.28,该如何解决问题?
我正在使用Python 2.7,并且我拥有的代码如下:
a = 10.5 * 22.34 / 2.0
print "%.2f" % a
我预期的结果是117.29,但显示为117.28,该如何解决问题?
def round_exact(number, decimal_places=0):
"""Round the number to the given number of decimal places by converting to
and from integers to avoid floating point error."""
factor = 10**(decimal_places + 1)
rounded_int = int(number * factor)
if rounded_int % 10 >= 5:
# Round up
return (int(rounded_int//10) + 1) / float(factor//10)
# Round down
return int(rounded_int//10) / float(factor//10)
print a
输出 "117.285"。更奇怪的是,print "%.4f" % 117.285
输出 "117.2850"。 - Nathan Ernstdouble
作为其浮点类型,而117.285
的确就在其下面。 (参见'%.18f'%117.285
。) 此外,Python还使用银行家舍入法,您可以通过比较'%.0f'%0.5
和'%.0f'%1.5
来了解。 - Thomas Wouters