Arg*_*rgo 3 python rounding python-2.7
如何将数字四舍五入到最接近的上下5万?
我想这一轮542756到此550000,或这一轮521405到此500000.考虑要舍入的数字是变量x.
我试过这个:
import math
def roundup(x):
return int(math.ceil(x / 50000.0)) * 50000
Run Code Online (Sandbox Code Playgroud)
但它只是四舍五入,我需要向上或向下四舍五入.
我也试过这个:
round(float(x), -5)
Run Code Online (Sandbox Code Playgroud)
但这轮到最近的十万.
我想有一个简单的解决方案但找不到任何东西.
您可以使用:
def round_nearest(x,num=50000):
return int(round(float(x)/num)*num)
Run Code Online (Sandbox Code Playgroud)
如果处理大数字,也可以避免转换为浮点数.在这种情况下,您可以使用:
def round_nearest_large(x,num=50000):
return ((x+num//2)//num)*numRun Code Online (Sandbox Code Playgroud)
您可以使用两个参数调用它来舍入到最近num,或者不会舍入到最接近的50000. int(..)如果您不希望结果int(..)本身(例如,如果您想要舍入0.5),则可以省略.在这种情况下,我们可以定义:
def round_nearest_float(x,num=50000):
return round(float(x)/num)*numRun Code Online (Sandbox Code Playgroud)
这会产生:
>>> round_nearest(542756)
550000
>>> round_nearest(521405)
500000
Run Code Online (Sandbox Code Playgroud)
或者,如果您想要另一个数字舍入到:
>>> round_nearest(542756,1000)
543000
>>> round_nearest(542756,200000)
600000
Run Code Online (Sandbox Code Playgroud)