始终将数字四舍五入到更大的一边
Always round up a number to a bigger side
我是 Python 的新手,我正在尝试将数字四舍五入到 10000
比例。
例如:
a = 154795
b = a / 10000 # 15.4795
c = round(b) # 15
我想将 c
舍入为 16
,即使 b = 15.0001
也如此,或者在将其传递给 [=17= 之前将 a
舍入为 160000
].
我怎样才能做到这一点?
感谢您的建议。
您可以使用math
的功能ceil
。
这是一个例子:
import math
a = 150001
b = a / 10000
print(math.ceil(b))
输出:
16
当然如果你想存储变量那么你可以使用:
import math
a = 15001
b = math.ceil(a / 1000)
print(b)
对于相同的输出:
16
您应该使用 python
中 math
模块的 ceil
函数
math.ceil() function returns the smallest integral value greater than
the number. If number is already integer, same number is returned.
from math import ceil
a = 154795
b = a / 10000 # 15,4795
c = ceil(b) # 16
print(c)
@Dschoni 说的。
import numpy as np
a = 154795
b = a / 10000 # 15,4795
c = np.ceil(b) # always rounds up. Gives 16 here
标准整数运算方式向上取整正整数N
除以D
(强调上,正数)是
(N + D - 1) // D
新的分子项是不会滚动到除数 D
的 下一个 倍数的最大值,这意味着我们可以使用整数除法.例如
def nquot(n, d):
# next quotient (I couldn't think of a better name)
return (n + d - 1) // d
>>> nquot(150000, 10000)
15
>>> nquot(150001, 10000)
16
允许转换为浮点数并在那里进行舍入通常更容易,就像其他答案中的 math.ceil
一样。
PS。你的数字分组很奇怪。 a,bbb,ccc
和a.bbb.ccc
都很熟悉,但是a.bbbc
不熟悉。
我是 Python 的新手,我正在尝试将数字四舍五入到 10000
比例。
例如:
a = 154795
b = a / 10000 # 15.4795
c = round(b) # 15
我想将 c
舍入为 16
,即使 b = 15.0001
也如此,或者在将其传递给 [=17= 之前将 a
舍入为 160000
].
我怎样才能做到这一点?
感谢您的建议。
您可以使用math
的功能ceil
。
这是一个例子:
import math
a = 150001
b = a / 10000
print(math.ceil(b))
输出:
16
当然如果你想存储变量那么你可以使用:
import math
a = 15001
b = math.ceil(a / 1000)
print(b)
对于相同的输出:
16
您应该使用 python
中math
模块的 ceil
函数
math.ceil() function returns the smallest integral value greater than the number. If number is already integer, same number is returned.
from math import ceil
a = 154795
b = a / 10000 # 15,4795
c = ceil(b) # 16
print(c)
@Dschoni 说的。
import numpy as np
a = 154795
b = a / 10000 # 15,4795
c = np.ceil(b) # always rounds up. Gives 16 here
标准整数运算方式向上取整正整数N
除以D
(强调上,正数)是
(N + D - 1) // D
新的分子项是不会滚动到除数 D
的 下一个 倍数的最大值,这意味着我们可以使用整数除法.例如
def nquot(n, d):
# next quotient (I couldn't think of a better name)
return (n + d - 1) // d
>>> nquot(150000, 10000)
15
>>> nquot(150001, 10000)
16
允许转换为浮点数并在那里进行舍入通常更容易,就像其他答案中的 math.ceil
一样。
PS。你的数字分组很奇怪。 a,bbb,ccc
和a.bbb.ccc
都很熟悉,但是a.bbbc
不熟悉。