JavaScript intval function
A JavaScript equivalent of PHP’s intval
function intval (mixed_var, base) {
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: stensi
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: Matteo
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Rafał Kukawski (http://kukawski.pl)
// * 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;
}
}
Example 1
intval('Kevin van Zonneveld');
Should return
0
Example 2
intval(4.2);
Should return
4
Example 3
intval(42, 8);
Should return
42
Комментарии:
Нету комментариев для вывода...