Last active
March 8, 2019 02:36
-
-
Save westc/9553052 to your computer and use it in GitHub Desktop.
Convert numbers to integers with cint().
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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)}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.yourjs.com/console/?gist=9553052&file=cint.js