Author: Steven Neiland
Published:

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.

What Do You Think?

Reader Comments

James Moberg's Gravatar
James Moberg
Wednesday, February 12, 2014 at 12:23:47 PM EST

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/

Post a Comment

Comment Etiquette:

  • 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 or appear to be advertisments, will not be published.
  • Comments that appear to be created for the purpose of linkbuilding to commercial sites will be removed.

We are all adults here so play nice.

*
*



Archives Blog Listing

Tag Listing

Learn CF In A Week

 
Fork me on GitHub