Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if character is number?

Tags:

javascript

You could use comparison operators to see if it is in the range of digit characters:

var c = justPrices[i].substr(commapos+2,1);
if (c >= '0' && c <= '9') {
    // it is a number
} else {
    // it isn't
}

you can either use parseInt and than check with isNaN

or if you want to work directly on your string you can use regexp like this:

function is_numeric(str){
    return /^\d+$/.test(str);
}

EDIT: Blender's updated answer is the right answer here if you're just checking a single character (namely !isNaN(parseInt(c, 10))). My answer below is a good solution if you want to test whole strings.

Here is jQuery's isNumeric implementation (in pure JavaScript), which works against full strings:

function isNumeric(s) {
    return !isNaN(s - parseFloat(s));
}

The comment for this function reads:

// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN

I think we can trust that these chaps have spent quite a bit of time on this!

Commented source here. Super geek discussion here.


I wonder why nobody has posted a solution like:

var charCodeZero = "0".charCodeAt(0);
var charCodeNine = "9".charCodeAt(0);

function isDigitCode(n) {
   return(n >= charCodeZero && n <= charCodeNine);
}

with an invocation like:

if (isDigitCode(justPrices[i].charCodeAt(commapos+2))) {
    ... // digit
} else {
    ... // not a digit
}

Simple function

function isCharNumber(c) {
  return c >= '0' && c <= '9';
}