JavaScript isNumeric()

Published: {ts '2014-01-21 00:00:00'}
Author: Steven Neiland
Site Url: http://www.neiland.net/article/javascript-isnumeric/

Sometimes javascript can be really smart and sometimes it can be really dumb. For example there is no built in function for determining if a value is actually numeric. Happily though the internet provides. This handy code snippet comes courtesy of Kris Korsmo

function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); }

Breaking it down

For the fun of it lets break it down.

parseFloat

The parseFloat() function parses a string and returns a floating point number.

parseFloat(n)

Rules:

  1. Only the first number in the string is returned!
  2. Leading and trailing spaces are allowed.
  3. If the first character cannot be converted to a number, parseFloat() returns NaN.

isNan()

The isNaN() function determines whether a value is an illegal number (Not-a-Number), returning true if the value is NaN, and false if not.

isFinite()

The isFinite() function determines whether a number is a finite, legal number.

Tip: This function returns false if the value is +infinity, -infinity, or NaN.