8
$\begingroup$

I found this and this on this StackExchange as to why Mathematica rounds half to even, which means that

Round[{0.5, 1.5, 2.5, 3.5, 4.5}] 

gives

{0, 2, 2, 4, 4} 

but now I am interested in rounding half down, which would be a function such that

RoundDown[{7.49, 7.5, 7.51}] 

gives

{7, 7, 8} 

I don't think it exists since I searched a lot and didn't find anything, so I was wondering as to how would one code such a function efficiently (I need to run it some millions of times)?

$\endgroup$

2 Answers 2

12
$\begingroup$
ClearAll[roundDown] roundDown = Ceiling[# - 1/2] &; (* thanks: @MichaelE2 *) roundDown @ {7.4999, 7.5, 7.51} (* or roundDown[{7.4999, 7.5, 7.51}] *) 

{7, 7, 8}

$\endgroup$
5
  • $\begingroup$ That's short and efficient, thanks! As a note for future users it also works with roundDown[{7.4999, 7.5, 7.51}] $\endgroup$ Commented Jan 3, 2018 at 6:48
  • $\begingroup$ @viiv, my pleasure. Thank you for the accept. $\endgroup$ Commented Jan 3, 2018 at 7:00
  • 1
    $\begingroup$ @viiv One might want to use 1/2 instead of 0.5. E.g. try rd1 = Ceiling[# - 1/2] &; rd2 = Ceiling[# - 0.5] &; {rd1[3/2 + 2^-53], rd2[3/2 + 2^-53]}. $\endgroup$ Commented Feb 20, 2018 at 12:17
  • $\begingroup$ @MichaelE2, very good point. $\endgroup$ Commented Feb 20, 2018 at 12:27
  • $\begingroup$ Indeed, it's all about those edge cases. Fortunately I never went that deep into the precision, I was limited to floats. $\endgroup$ Commented Feb 20, 2018 at 12:46
2
$\begingroup$

Adding a note to kglr's answer, consider

n = 50*4.65 roundDown[n] 

233

An improvement could be

rd[n_] := Ceiling[With[{r = Round[#]}, r + Chop[# - r]] &[n - 0.5]] rd[n] 

232

$\endgroup$
2
  • $\begingroup$ But 50*4.65 equals 232.50000000000003` , so shouldn't it round to 233? What if the number is exactly 232.50000000000003? $\endgroup$ Commented Feb 20, 2018 at 12:59
  • $\begingroup$ In practical situations I have encountered I would require 50*4.65 = 232.5. $\endgroup$ Commented Feb 20, 2018 at 13:07

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.