The JavaScript IsNumeric Function

isNumeric

Today I wrote a (very small) node package to allow you to determine if a JavaScript object is numeric or not. It turns out it’s really not a lot of code, but took a little while to get just right. It’s tested with every type of numeric I could think up (and also non-numerics).

Using npm

1
npm install isnumeric

To then include isnumeric in your node app:

1
var isNumeric = require("isnumeric");

Direct dependency

Download the minified version here, reference the js file and isNumeric will become a global variable.

The code

Essentially, this is it:

isNumeric
1
2
3
4
var isNumeric = function (obj) {
obj = typeof(obj) === "string" ? obj.replace(",", ".") : obj;
return !isNaN(parseFloat(obj)) && isFinite(obj) && Object.prototype.toString.call(obj).toLowerCase() !== "[object array]";
};

The first line of the function could be omitted if you weren’t concerned with supporting comma decimals (e.g. “1,1”) like in some countries.

The tests

There are currently 64 tests! so it’s pretty well tested. I certainly win the award for smallest amount of code with most amount of tests :)

Any disagreements or improvements please pull request.