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))

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值