如何使用python四舍五入?保留n位小数的最佳方法
功能:
将数字四舍五入到指定的位数。
代码:
from decimal import Decimal, ROUND_HALF_UP
def round_up(number, num_digits):
"""
按指定位数对数值进行四舍五入。
:param number:要四舍五入的数字。
:param num_digits:要进行四舍五入运算的位数。
:return:返回结果。
"""
if num_digits > 0:
res = round_up(number * 10, num_digits - 1) / 10
else:
res = Decimal(number * 10 ** num_digits).quantize(Decimal('1'), rounding=ROUND_HALF_UP) * 10 ** -num_digits
return res
print(round_up(3.141592653589793, 5))
print(round_up(3.141592653589793, 0))
print(round_up(31415926535897933, -7))
print('')
print('round:')
print(round(0.105, 2))
print(round(1.115, 2))
print(round(0.125, 2))
print(round(0.0115, 3))
print(round(-0.625, 2))
print(round(-2.635, 2))
print('')
print('round_up:')
print(round_up(0.105, 2))
print(round_up(1.115, 2))
print(round_up(0.125, 2))
print(round_up(0.0115, 3))
print(round_up(-0.625, 2))
print(round_up(-2.635, 2))
运行结果:
3.14159
3
31415926540000000
round:
0.1
1.11
0.12
0.011
-0.62
-2.63
round_up:
0.11
1.12
0.13
0.012
-0.63
-2.64
Process finished with exit code 0
备注:
- number 必需。 要四舍五入的数字。
- num_digits 必需。 要进行四舍五入运算的位数。
- 如果 num_digits 大于 0(零),则将数字四舍五入到指定的小数位数。
- 如果 num_digits 等于 0,则将数字四舍五入到最接近的整数。
- 如果 num_digits 小于 0,则将数字四舍五入到小数点左边的相应位数。