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

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





math.floor()?
– dhke
Aug 23 at 5:40


math.floor()





How much do you want to round it downwards? I mean is not the same to go on units, decimal, hunderds, thousands.
– jalazbe
Aug 23 at 5:45





This should help: stackoverflow.com/q/34030509/2988730
– Mad Physicist
Aug 23 at 5:50





Possible duplicate of Python Rounding Down to Custom Step
– Thomas
Aug 23 at 6:33





Did an answer below help? If so, please consider accepting (green tick on the left).
– jpp
Aug 26 at 11:45




3 Answers
3



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



Maybe you can try it this way


import math
math.floor(1900 / 100) * 100





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. :-)
– Thomas
Aug 23 at 6:42



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



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)






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)