Skip to content

Instantly share code, notes, and snippets.

@Olical
Created August 22, 2011 14:05
Show Gist options
  • Save Olical/1162452 to your computer and use it in GitHub Desktop.
Save Olical/1162452 to your computer and use it in GitHub Desktop.
Very fast rounding in JavaScript
Number.round = function() {
return (this + 0.5) << 0;
};
@algj
Copy link

algj commented Nov 3, 2018

This works fine with negative numbers.

Number.round = function() {
    return (this + (this>0?0.5:-0.5)) << 0;
};

@DoctypeRosenthal
Copy link

DoctypeRosenthal commented Apr 25, 2019

Thanks for the trick!
You know what surprised me? That when you put the bitshifting stuff in a function, it is faster than applying it every time on the number literally. Have a look:

(() =>{
  const time = f => {
    let start = Date.now()
    f()
    console.log('Needed ', Date.now() - start, ' ms')
  }
  const round = x => x + 0.5 << 0
  const N = 10000000

  console.log("Testing O(n) for rounding with n =",N)
  
  console.log("Math.round\n")
  time(() => {
    for (let i = 1; i <= N; i++)
      Math.round(50/i)
  })

  console.log("bit shift\n")
  time(() => {
    for (let i = 1; i <= N; i++)
      (50/i) + 0.5 << 0
  })

  console.log("bit shift in own function\n")
  time(() => {
    for (let i = 1; i <= N; i++)
      round(50/i)
  })

})()

gave me this in newest Firefox:

Testing O(n) for rounding with n = 10000000 

Math.round
Needed  690  ms 

bit shift
Needed  10 

bit shift in own function
Needed  8  ms 

In node.js however it is nearly identical speed for all of them:

Testing O(n) for rounding with n = 1000000

Math.round
Needed  3  ms

bit shift
Needed  1  ms

bit shift in own function
Needed  1  ms



Testing O(n) for rounding with n = 10000000

Math.round
Needed  8  ms

bit shift
Needed  6  ms

bit shift in own function
Needed  6  ms



Testing O(n) for rounding with n = 100000000

Math.round
Needed  52  ms

bit shift
Needed  50  ms

bit shift in own function
Needed  52  ms



Testing O(n) for rounding with n = 1000000000

Math.round
Needed  500  ms

bit shift
Needed  501  ms

bit shift in own function
Needed  495  ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment