In python, there's a builtin function round(),
it rounds a number like this:
在python中,有一个内置函数round(),它舍入一个这样的数字:
round(1900, -3) == 2000
is there a builtin function that can round a number downward, like this:
是否有一个内置函数可以向下舍入一个数字,如下所示:
function(1900, -3) == 1000
3 个解决方案
#1
2
You can use floor division:
您可以使用楼层划分:
def round_down(x, k=3):
n = 10**k
return x // n * n
res = round_down(1900) # 1000
math.floor
will also work, but with a drop in performance, see Python integer division operator vs math.floor.
math.floor也可以工作,但性能下降,请参阅Python整数除法运算符与math.floor。
#2
1
Maybe you can try it this way
也许你可以这样试试
import math
math.floor(1900 / 100) * 100
#3
0
math.floor([field])
rounds down to next integer
math.floor([field])向下舍入到下一个整数
math.ceil([field]/1000)*1000
rounds down to next 1000
math.ceil([field] / 1000)* 1000向下舍入到下一个1000
Maybe you could make an int cast after that.
也许你可以在那之后做一个int cast。
if you like your syntax with the exponent parameter you could define your own function:
如果您喜欢使用exponent参数的语法,则可以定义自己的函数:
import math
def floorTo10ths(number, exp):
return int(math.floor(number/10**exp) * 10**exp)
floorTo10ths(1900, 3)
#1
2
You can use floor division:
您可以使用楼层划分:
def round_down(x, k=3):
n = 10**k
return x // n * n
res = round_down(1900) # 1000
math.floor
will also work, but with a drop in performance, see Python integer division operator vs math.floor.
math.floor也可以工作,但性能下降,请参阅Python整数除法运算符与math.floor。
#2
1
Maybe you can try it this way
也许你可以这样试试
import math
math.floor(1900 / 100) * 100
#3
0
math.floor([field])
rounds down to next integer
math.floor([field])向下舍入到下一个整数
math.ceil([field]/1000)*1000
rounds down to next 1000
math.ceil([field] / 1000)* 1000向下舍入到下一个1000
Maybe you could make an int cast after that.
也许你可以在那之后做一个int cast。
if you like your syntax with the exponent parameter you could define your own function:
如果您喜欢使用exponent参数的语法,则可以定义自己的函数:
import math
def floorTo10ths(number, exp):
return int(math.floor(number/10**exp) * 10**exp)
floorTo10ths(1900, 3)