美文网首页
Python3 四舍五入(浮点数执行指定精度的舍入运算)

Python3 四舍五入(浮点数执行指定精度的舍入运算)

作者: 盖码范 | 来源:发表于2019-08-05 16:23 被阅读0次

数字的四舍五入

使用round(value, ndigits)函数

>>> round(1.23, 1)
1.2
>>> round(1.27, 1)
1.3
>>> round(-1.27, 1)
-1.3
>>> round(1.25361,3)
1.254
>>>

传给 round() 函数的 ndigits 参数可以是负数,这种情况下, 舍入运算会作用在十位、百位、千位等上面。比如:

>>> a = 1627731
>>> round(a, -1)
1627730
>>> round(a, -2)
1627700
>>> round(a, -3)
1628000
>>>

讨论

那么问题来了,如果我不需要四舍五入,不更改最后一位的值。例如:

>>> x = 1.23456
>>> format(x, '0.2f')
'1.23'
>>> format(x, '0.3f')
'1.235'
>>> 'value is {:0.3f}'.format(x)
'value is 1.235'
>>>

相关文章

网友评论

      本文标题:Python3 四舍五入(浮点数执行指定精度的舍入运算)

      本文链接:https://www.haomeiwen.com/subject/ysthdctx.html