python学习笔记: round()函数及相关

一、round(x [ , n ]):返回x(可以为数值或运算表达式)的四舍五入值,保留n位小数。

Note1 :当小数点后正好为5时,round(X.5)=X或者X+1(trap!)

***在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。

Note2:当小数点后有多位小数时,round()结果无法确定!!

***“The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.”

二、四舍五入

import decimal
#四舍五入
def roundHalfUp(d):
    rounding=decimal.ROUND_HALF_UP
    return int(decimal.Decimal(d).to_integral_value(rounding=rounding))

三、五舍六入

import decimal
def roundHalfDown(d):
    rounding=decimal.ROUND_HALF_DOWN
    return int(decimal.Decimal(d).to_integral_value(rounding=rounding))

猜你喜欢

转载自blog.csdn.net/xiaozhimonica/article/details/82908647