Symmetric Rounding

Benchmark created on


Description

-20.5 rounds to -20, but what if it rounded to -21?

Preparation HTML

<script>

const CASES = [];
const N = 1000;
// on values ±1000000
const R = 1000000;
const R2 = 2 * R;

for (let i = 0; i < N; i++) {
  CASES.push(Math.random() * 2 * R - R);
}


</script>

Setup


function test (f) {
  for (const n of CASES) f(n);
}

// round the magnitude then multiply by the sign
function round1 (n) {
  return Math.round(Math.abs(n)) * Math.sign(n);
}

// conditionally use floor for negative numbers
// with a fractional part of 0.5
function round2 (n) {
  return n >= 0 ? Math.round(n) :
    n % 0.5 === 0 ? Math.floor(n) : 
    Math.round(n);	
}

// same as 2 w/ slightly different conditional
function round3 (n) {
  return (n >= 0 || n % 0.5 !== 0) ?
    Math.round(n) :
    Math.floor(n);
}

Test runner

Ready to run.

Testing in
TestOps/sec
round magnitude * sign
test(round1);
ready
conditional floor
test(round2);
ready
same as 2 w/ consolidated condition
test(round3);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.