0

Is there a simple way to round in python to the nearest X value? For example, to round to the nearest tens I can do:

>>> round(1845,-1)
1840

What about if I wanted to round to the nearest...?

# round down when there's ambiguity
number = 1845
round(10, 1845) ==> 1840
round(5, 1845)  ==> 1845
round(2, 1845)  ==> 1844
round(50, 1845) ==> 1850
etc.

>>> round = lambda multiple, number: (number // multiple) * multiple
>>> round(1855, 10)
1850

Should work (partially -- always rounds down, see comment below), but wondering any other solutions (just for fun) ?

carl.hiass
  • 1,526
  • 1
  • 6
  • 26
  • In your function `round`, shouldn't 1855 round to 1860? – jkr Sep 02 '20 at 21:25
  • If you're asking how this can be done differently, that's just an open problem, if you're asking how can this be done better, it's asking for an opinion or a review - neither is really at home on StackOverflow. Also, don't name lambdas - that's what `def` is for. – Grismar Sep 02 '20 at 21:25
  • @jakub -- in the first part I was just using the builtin `round` function in python. – carl.hiass Sep 02 '20 at 21:26
  • 1
    `(1845 // 50) * 50` is not `1850` – DeepSpace Sep 02 '20 at 21:26
  • @DeepSpace good point -- I think my function gets the greatest multiple less than...which is not what I want, I only want it to round down if there's an even split, so yes my current implementation is wrong. – carl.hiass Sep 02 '20 at 21:28

0 Answers0