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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With