JavaScript isNumeric()

Author: Steven Neiland
Published:

Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

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.

Reader Comments

James Moberg's Gravatar
James Moberg
Wednesday, February 12, 2014 at 12:23:47 PM Coordinated Universal Time

This is the same logic used by jQuery 1.7:
https://api.jquery.com/jQuery.isNumeric/

Thanks for explaining it further! I've requested that the IsNumeric function in CFJS javascript library be updated to be consistent with jQuery.
http://cfjs.riaforge.org/

/df's Gravatar
/df
Sunday, December 4, 2016 at 8:24:29 AM Coordinated Universal Time

Fails on a string like "123.456xyz".

Steven Neiland's Gravatar
Steven Neiland
Sunday, December 4, 2016 at 10:23:51 AM Coordinated Universal Time

df. I just tested and it works for me. Please provide more details.

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

isNumeric("123.456xyz"); // correctly returns false

shari's Gravatar
shari
Friday, December 8, 2017 at 10:33:07 AM Coordinated Universal Time

how to use the isNumeric in javascript

  • Please keep comments on-topic.
  • Please do not post unrelated questions or large chunks of code.
  • Please do not engage in flaming/abusive behaviour.
  • Comments that contain advertisments or appear to be created for the purpose of link building, will not be published.

Archives Blog Listing