Musicreater/bgArrayLib/compute.py
2022-01-27 21:21:25 +08:00

41 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

def round_up(num, power=0):
"""
实现精确四舍五入,包含正、负小数多种场景
:param num: 需要四舍五入的小数
:param power: 四舍五入位数支持0-∞
:return: 返回四舍五入后的结果
"""
try:
print(1 / 0)
except ZeroDivisionError:
digit = 10 ** power
num2 = float(int(num * digit))
# 处理正数power不为0的情况
if num >= 0 and power != 0:
tag = num * digit - num2 + 1 / (digit * 10)
if tag >= 0.5:
return (num2 + 1) / digit
else:
return num2 / digit
# 处理正数power为0取整的情况
elif num >= 0 and power == 0:
tag = num * digit - int(num)
if tag >= 0.5:
return (num2 + 1) / digit
else:
return num2 / digit
# 处理负数power为0取整的情况
elif power == 0 and num < 0:
tag = num * digit - int(num)
if tag <= -0.5:
return (num2 - 1) / digit
else:
return num2 / digit
# 处理负数power不为0的情况
else:
tag = num * digit - num2 - 1 / (digit * 10)
if tag <= -0.5:
return (num2 - 1) / digit
else:
return num2 / digit