python3中round的用法_浅谈python3中的round函数

在很多人眼里,round可能是一个四舍五入函数,但到了python3当中并没有你想的那么简单,这已经不再是一个高精度的四舍五入函数了,可能计算的结果会让你出乎意料。

首先看一段代码:

# coding=utf-8

a = 1.2345

b = 1.23456

c = 1.2335

print(str(a) + "取后三位结果: " + str(round(a, 3)))

print(str(b) + "取后三位结果: " + str(round(b, 3)))

print(str(c) + "取后三位结果: " + str(round(c, 3)))

运行结果:

1.2345取后三位结果: 1.234

1.23456取后三位结果: 1.235

1.2335取后三位结果: 1.234

发现python3并没有进行四舍五入,为什么呢?

去翻阅python3的文档,有这么一段话:

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.

大概意思是:如果距离两边一样远,会保留到偶数的一边。

比如round(0.5)和round(-0.5)都会保留到0,而round(1.5)会保留到2

那么根据这个解释来讲,a b c的结果

你可能感兴趣的:(python3中round的用法_浅谈python3中的round函数)