5

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
jpp
  • 159,742
  • 34
  • 281
  • 339

4 Answers4

4

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.

jpp
  • 159,742
  • 34
  • 281
  • 339
2

Maybe you can try it this way

import math
math.floor(1900 / 100) * 100
Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
moonscar
  • 21
  • 2
  • Looks good (+1). The idea from user 侯月源 is to bring it to the precision level you want to round for (change the order of magnitude) and then do the inverse operation after rounding. 侯月源 the only thing left is to put it into a function to suite the OP's needs. :-) – tafaust Aug 23 '18 at 06:42
0

math.floor([field]) rounds down to next integer

math.ceil([field]/1000)*1000 rounds down to next 1000

Maybe you could make an int cast after that.

if you like your syntax with the exponent parameter you could define your own function:

import math

def floorTo10ths(number, exp):
     return int(math.floor(number/10**exp) * 10**exp) 

floorTo10ths(1900, 3)
S-Man
  • 22,521
  • 7
  • 40
  • 63
0
def arroundSup(number, power) :
   nbr = number / (1000*power)
   return ceil(nbr) * (1000*power)


arroundSup(1900, 3) # will return 2000

---------------------------------------------------

def arroundLow(number, power) :
   nbr = number / (1000*power)
   return floor(nbr) * (1000*power)


arroundLow(1900, 3) # will return 1000