Check if character is number?
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.