[00301]数字的四舍五入

数字的四舍五入

一、 解决问题

对浮点数执行指定精度的舍入运算。

二、解决方案

使用内置函数 round(value, ndigits)

三、代码说明

"""
当一个值刚好在两边边界的中间时,
round() 函数返回离它最近的偶数
round(1.5) == round(2.5)  == 2
"""

print (round(1.23, 1)) #->1.2
print (round(1.27, 1)) #->1.3
print (round(1.5)) #->2
print (round(2.5)) #->2


"""
传递给round() 可以为负数: 舍入运算作用域十位,百位....
"""
print (round(154784, -2)) #->154800
"""
如果目的只是简单的输出一定的宽度,不要使用round()函数
格式化操作
"""
x = 1.296
print (round(x, 2)) #->1.3
print (format(x, '0.2f')) #->1.30
print ("value is {0:0.3f}".format(x)) #->value is 1.296
"""
不要使用 round() 来修正运算结果
"""
a = 2.1
b = 4.2
c = a + b
print (c) #->6.300000000000001
print (round(c, 2)) #-> 不推荐使用 

"""
使用decimal 模块解决午误差问题
"""

四、关联知识

五、总结

六、代码地址

github地址:https://github.com/weichen666/python_cookbooka>
目录/文件:third_selection/learn_data_date_time_round.py

七、参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值