Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function that only rounds down?

Outside of coding my own, is there any built in Python function that only rounds integers down? I'm looking for something with a similar function to the round() function, but would, say, evaluate

myFunction(3900, -3) 

as 3000, not 4000.

And, if there is no built in function fitting that description, do you have any advice for coding my own?

like image 992
Elizabeth Yohe Avatar asked May 02 '26 14:05

Elizabeth Yohe


1 Answers

You can use this simple trick: substract half a decade/hundred/thousand/etc. based on the required precision and use the round() builtin.

This would give you something like this:

>>> round_down = lambda x, prec: round(x - 5 * (10 ** (prec - 1)) + 1, -prec)
>>> round_down(2900, 3)
2000
>>> round_down(290, 2)
200

Notice that when substracting, you have to add 1 to the number to be passed to round, because otherwise in the extreme case where you called

round_down(3000, 3)

you would actually be calling

round(2500, -3)

which would evaluate to 2000.

like image 133
VHarisop Avatar answered May 04 '26 04:05

VHarisop