Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how can I round a number downward to next 1000

In python, there's a builtin function 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
like image 809
David Avatar asked Aug 23 '18 05:08

David


1 Answers

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.

like image 117
jpp Avatar answered Sep 29 '22 06:09

jpp