Skip to content

Instantly share code, notes, and snippets.

@westc
Last active March 8, 2019 02:36
Show Gist options
  • Save westc/9553052 to your computer and use it in GitHub Desktop.
Save westc/9553052 to your computer and use it in GitHub Desktop.
Convert numbers to integers with cint().
/**
* @license Copyright 2019 - Chris West - MIT Licensed
*
* Converts a number into an integer.
* @param {*} num
* The value to convert into an integer.
* @param {boolean|null} opt_infinityBiased
* Optional. If a true-ish value is specified the number will be rounded
* towards `Infinity` if positive or `-Infinity` if negative. If not given,
* or if `null` or `undefined` is specified the number will be rounded. If
* a false-ish value is specified the number will be rounded towards `0`.
* @return {number}
* The integer version of the specified number.
*/
function cint(num, opt_infinityBiased) {
num = +num;
return Math[opt_infinityBiased == null ? 'round' : (num < 0) === !opt_infinityBiased ? 'ceil' : 'floor'](num);
}
console.log(`cint(${x = 1.3}, ${y = true}) -> ${cint(x, y)}`);
console.log(`cint(${x = -1.3}, ${y = true}) -> ${cint(x, y)}`);
console.log(`cint(${x = 2.7}, ${y = false}) -> ${cint(x, y)}`);
console.log(`cint(${x = -2.7}, ${y = false}) -> ${cint(x, y)}`);
console.log(`cint(${x = 3.499}) -> ${cint(x)}`);
console.log(`cint(${x = -3.499}) -> ${cint(x)}`);
console.log(`cint(${x = 3.5}) -> ${cint(x)}`);
console.log(`cint(${x = -3.5}) -> ${cint(x)}`);
console.log(`cint(${x = 3.501}) -> ${cint(x)}`);
console.log(`cint(${x = -3.501}) -> ${cint(x)}`);
@westc
Copy link
Author

westc commented Mar 8, 2019

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