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

2019-08-05  本文已影响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'
>>>
上一篇 下一篇

猜你喜欢

热点阅读