Skip to content

Instantly share code, notes, and snippets.

@paulhhowells
Last active December 16, 2015 11:49
Show Gist options
  • Select an option

  • Save paulhhowells/5430476 to your computer and use it in GitHub Desktop.

Select an option

Save paulhhowells/5430476 to your computer and use it in GitHub Desktop.
rounding functions
phh = phh || {};
phh.round = function (n) {
return ~~((n >= 0 ? n : -n) + 0.5);
};
phh.ceil = function (n) {
// faster than Math.ceil, but only behaves the same when testing positive numbers
// http://jsperf.com/math-ceil/4
return (n === ~~n) ? n : ~~n + 1;
};
phh.swingCeil = function (n) {
// rounds to an integer
// +ve numbers swing away from 0 (towards Ceiling)
// -ve numbers swing away from 0
// 5.2 -> 6
// -5.2 -> -6
return (n === ~~n) ? n : ~~n + ((n > 0) ? 1 : -1);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment