phpjs
Version:
34 lines (31 loc) • 1.01 kB
JavaScript
function intval(mixed_var, base) {
// discuss at: http://phpjs.org/functions/intval/
// original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: stensi
// bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: Rafał Kukawski (http://kukawski.pl)
// input by: Matteo
// example 1: intval('Kevin van Zonneveld');
// returns 1: 0
// example 2: intval(4.2);
// returns 2: 4
// example 3: intval(42, 8);
// returns 3: 42
// example 4: intval('09');
// returns 4: 9
// example 5: intval('1e', 16);
// returns 5: 30
var tmp;
var type = typeof mixed_var;
if (type === 'boolean') {
return +mixed_var;
} else if (type === 'string') {
tmp = parseInt(mixed_var, base || 10);
return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
} else if (type === 'number' && isFinite(mixed_var)) {
return mixed_var | 0;
} else {
return 0;
}
}