Search This Blog

Wednesday, March 13, 2013

Validate numbers in JavaScript - IsNumeric()


If You need an IsNumeric function, to find out if a variable contained a numeric value, regardless its type, it could be a String containing a numeric value (I had to consider also exponential notation, etc.), a Number object, virtually anything could be passed to that function, I couldn't make any type assumption, taking care of type coercion (eg. +true == 1; but true shouldn't be considered as"numeric").
I think is worth sharing this set of +30 unit tests made to numerous function implementations, and also share the one that passes all my tests:
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

No comments:

Post a Comment