如何舍入 Python 中的数字(逗号后的许多数字)
How to round number in Python (many digits after comma)
如何打印具有 2.6000000000000001 的 2.7。 (或任何其他类似的数字)。
import math
print(math.ceil(2.6000000000000001)) // 3
print(round(2.6000000000000001, 2)) // 2.6
???
import math
num=2.6000000000000001
digits=1
t1=10**digits
math.ceil(num*t1)/t1
如果您想以通用的方式为不同的位数执行此操作,here 是一个关于如何定义相应函数的示例:
import math
def round_decimals_up(number:float, decimals:int=1):
if not isinstance(decimals, int):
raise TypeError("decimal places must be an integer")
elif decimals < 0:
raise ValueError("decimal places needs to be 0 or more")
elif decimals == 0:
return math.ceil(number)
factor = 10 ** decimals
return math.ceil(number * factor) / factor
我将其修改为默认为一位小数,但它也允许您指定位数:
x = 2.6
y = 2.60000000001
print(round_decimals_up(x))
print(round_decimals_up(y))
print(round_decimals_up(x,2))
print(round_decimals_up(y,2))
产量
2.6
2.7
2.6
2.61
如何打印具有 2.6000000000000001 的 2.7。 (或任何其他类似的数字)。
import math
print(math.ceil(2.6000000000000001)) // 3
print(round(2.6000000000000001, 2)) // 2.6
???
import math
num=2.6000000000000001
digits=1
t1=10**digits
math.ceil(num*t1)/t1
如果您想以通用的方式为不同的位数执行此操作,here 是一个关于如何定义相应函数的示例:
import math
def round_decimals_up(number:float, decimals:int=1):
if not isinstance(decimals, int):
raise TypeError("decimal places must be an integer")
elif decimals < 0:
raise ValueError("decimal places needs to be 0 or more")
elif decimals == 0:
return math.ceil(number)
factor = 10 ** decimals
return math.ceil(number * factor) / factor
我将其修改为默认为一位小数,但它也允许您指定位数:
x = 2.6
y = 2.60000000001
print(round_decimals_up(x))
print(round_decimals_up(y))
print(round_decimals_up(x,2))
print(round_decimals_up(y,2))
产量
2.6
2.7
2.6
2.61