[英]Python: how can I round a number downward to next 1000
In python, there's a builtin function round(), 在python中,有一个内置函数round(),
it rounds a number like this: 它围绕一个这样的数字:
round(1900, -3) == 2000
is there a builtin function that can round a number downward, like this: 是否有一个内置函数可以向下舍入一个数字,如下所示:
function(1900, -3) == 1000
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 。
Maybe you can try it this way 也许你可以这样试试
import math
math.floor(1900 / 100) * 100
math.floor([field])
rounds down to next integer math.floor([field])
向下math.floor([field])
到下一个整数
math.ceil([field]/1000)*1000
rounds down to next 1000 math.ceil([field]/1000)*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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.