phpjs
Version:
88 lines (74 loc) • 2.55 kB
Markdown
layout: page
title: "JavaScript is_numeric function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/is_numeric:449
- /functions/view/is_numeric
- /functions/view/449
- /functions/is_numeric:449
- /functions/449
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's is_numeric
{% codeblock var/is_numeric.js lang:js https://raw.github.com/kvz/phpjs/master/functions/var/is_numeric.js raw on github %}
function is_numeric (mixed_var) {
// From: http://phpjs.org/functions
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: David
// + improved by: taith
// + bugfixed by: Tim de Koning
// + bugfixed by: WebDevHobo (http://webdevhobo.blogspot.com/)
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// * example 1: is_numeric(186.31);
// * returns 1: true
// * example 2: is_numeric('Kevin van Zonneveld');
// * returns 2: false
// * example 3: is_numeric('+186.31e2');
// * returns 3: true
// * example 4: is_numeric('');
// * returns 4: false
// * example 4: is_numeric([]);
// * returns 4: false
return (typeof mixed_var === 'number' || typeof mixed_var === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}
{% endcodeblock %}
- [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/var/is_numeric.js)
Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are
the closest match to this hashtable-like data structure.
Please also note that php.js offers community built functions and goes by the
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online
functions that are far from perfect, in the hopes to spark better contributions.
Do you have one? Then please just:
- [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/var/is_numeric.js)
### Example 1
This code
{% codeblock lang:js example %}
is_numeric(186.31);
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
true
{% endcodeblock %}
### Example 2
This code
{% codeblock lang:js example %}
is_numeric('Kevin van Zonneveld');
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
false
{% endcodeblock %}
### Example 3
This code
{% codeblock lang:js example %}
is_numeric('+186.31e2');
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
true
{% endcodeblock %}
### Other PHP functions in the var extension
{% render_partial _includes/custom/var.html %}