目录
round方法
对浮点数后的小数位数进行处理,第一个参数是一个浮点数,第二个参数是保留的小数位数,可选,如果不写的话默认保留到整数。
BMI=20.957438
BMI=round(BMI,1)
print(BMI)
运行结果:
注意:round的结果跟python版本有关
阅读一下python的文档,里面是这么写的:
在python2.7的doc中,round()的最后写着,"Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0." 保留值将保留到离上一位更近的一端(四舍六入),如果距离两端一样远,则保留到离0远的一边。所以round(0.5)会近似到1,而round(-0.5)会近似到-1。
但是到了python3.5的doc中,文档变成了"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。
所以如果有项目是从py2迁移到py3的,可要注意一下round的地方(当然,还要注意/和