[javascript] Check if character is number?

I need to check whether justPrices[i].substr(commapos+2,1).

The string is something like: "blabla,120"

In this case it would check whether '0' is a number. How can this be done?

This question is related to javascript

The answer is


Simple function

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

I think it's very fun to come up with ways to solve this. Below are some.
(All functions below assume argument is a single character. Change to n[0] to enforce it)

Method 1:

function isCharDigit(n){
  return !!n.trim() && n > -1;
}

Method 2:

function isCharDigit(n){
  return !!n.trim() && n*0==0;
}

Method 3:

function isCharDigit(n){
  return !!n.trim() && !!Number(n+.1); // "+.1' to make it work with "." and "0" Chars
}

Method 4:

var isCharDigit = (function(){
  var a = [1,1,1,1,1,1,1,1,1,1];
  return function(n){
    return !!a[n] // check if `a` Array has anything in index 'n'. Cast result to boolean
  }
})();

Method 5:

function isCharDigit(n){
  return !!n.trim() && !isNaN(+n);
}

Test string:

var str = ' 90ABcd#?:.+', char;
for( char of str ) 
  console.log( char, isCharDigit(char) );

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
}

square = function(a) {
    if ((a * 0) == 0) {
        return a*a;
    } else {
        return "Enter a valid number.";
    }
}

Source


Try:

function is_numeric(str){
        try {
           return isFinite(str)
        }
        catch(err) {
            return false
        }
    }

This seems to work:

Static binding:

String.isNumeric = function (value) {
    return !isNaN(String(value) * 1);
};

Prototype binding:

String.prototype.isNumeric = function () {
    return !isNaN(this.valueOf() * 1);
};

It will check single characters, as well as whole strings to see if they are numeric.


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.


You can use this:

function isDigit(n) {
    return Boolean([true, true, true, true, true, true, true, true, true, true][n]);
}

Here, I compared it to the accepted method: http://jsperf.com/isdigittest/5 . I didn't expect much, so I was pretty suprised, when I found out that accepted method was much slower.

Interesting thing is, that while accepted method is faster correct input (eg. '5') and slower for incorrect (eg. 'a'), my method is exact opposite (fast for incorrect and slower for correct).

Still, in worst case, my method is 2 times faster than accepted solution for correct input and over 5 times faster for incorrect input.


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
}

I suggest a simple regex.

If you're looking for just the last character in the string:

/^.*?[0-9]$/.test("blabla,120");  // true
/^.*?[0-9]$/.test("blabla,120a"); // false
/^.*?[0-9]$/.test("120");         // true
/^.*?[0-9]$/.test(120);           // true
/^.*?[0-9]$/.test(undefined);     // false
/^.*?[0-9]$/.test(-1);            // true
/^.*?[0-9]$/.test("-1");          // true
/^.*?[0-9]$/.test(false);         // false
/^.*?[0-9]$/.test(true);          // false

And the regex is even simpler if you are just checking a single char as an input:

var char = "0";
/^[0-9]$/.test(char);             // true

You can try this (worked in my case)

If you want to test if the first char of a string is an int:

if (parseInt(YOUR_STRING.slice(0, 1))) {
    alert("first char is int")
} else {
    alert("first char is not int")
}

If you want to test if the char is a int:

if (parseInt(YOUR_CHAR)) {
    alert("first char is int")
} else {
    alert("first char is not int")
}

Use combination of isNaN and parseInt functions:

var character = ... ; // your character
var isDigit = ! isNaN( parseInt(character) );

Another notable way - multiplication by one (like character * 1 instead of parseInt(character)) - makes a number not only from any numeric string, but also a 0 from empty string and a string containing only spaces so it is not suitable here.


var Is = {
    character: {
        number: (function() {
            // Only computed once
            var zero = "0".charCodeAt(0), nine = "9".charCodeAt(0);

            return function(c) {
                return (c = c.charCodeAt(0)) >= zero && c <= nine;
            }
        })()
    }
};

If you are testing single characters, then:

var isDigit = (function() {
    var re = /^\d$/;
    return function(c) {
        return re.test(c);
    }
}());

will return true or false depending on whether c is a digit or not.


function is_numeric(mixed_var) {
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') &&
        mixed_var !== '' && !isNaN(mixed_var);
}

Source code


The shortest solution is:

const isCharDigit = n => n < 10;

You can apply these as well:

const isCharDigit = n => Boolean(++n);

const isCharDigit = n => '/' < n && n < ':';

const isCharDigit = n => !!++n;

if you want to check more than 1 chatacter, you might use next variants

Regular Expression:

const isDigit = n => /\d+/.test(n);

Comparison:

const isDigit = n => +n == n;

Check if it is not NaN

const isDigit = n => !isNaN(n);

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);
}

A simple solution by leveraging language's dynamic type checking:

function isNumber (string) {
   //it has whitespace
   if(string.trim() === ''){
     return false
   }
   return string - 0 === string * 1
}

see test cases below

_x000D_
_x000D_
function isNumber (str) {
   if(str.trim() === ''){
     return false
   }
   return str - 0 === str * 1
}


console.log('-1' + ' ? ' + isNumber ('-1'))    
console.log('-1.5' + ' ? ' + isNumber ('-1.5')) 
console.log('0' + ' ? ' + isNumber ('0'))    
console.log(', ,' + ' ? ' + isNumber (', ,'))  
console.log('0.42' + ' ? ' + isNumber ('0.42'))   
console.log('.42' + ' ? ' + isNumber ('.42'))    
console.log('#abcdef' + ' ? ' + isNumber ('#abcdef'))
console.log('1.2.3' + ' ? ' + isNumber ('1.2.3')) 
console.log('' + ' ? ' + isNumber (''))    
console.log('blah' + ' ? ' + isNumber ('blah'))
_x000D_
_x000D_
_x000D_


isNumber = function(obj, strict) {
    var strict = strict === true ? true : false;
    if (strict) {
        return !isNaN(obj) && obj instanceof Number ? true : false;
    } else {
        return !isNaN(obj - parseFloat(obj));
    }
}

output without strict mode:

var num = 14;
var textnum = '14';
var text = 'yo';
var nan = NaN;

isNumber(num);
isNumber(textnum);
isNumber(text);
isNumber(nan);

true
true
false
false

output with strict mode:

var num = 14;
var textnum = '14';
var text = 'yo';
var nan = NaN;

isNumber(num, true);
isNumber(textnum, true);
isNumber(text, true);
isNumber(nan);

true
false
false
false

Similar to one of the answers above, I used

 var sum = 0; //some value
 let num = parseInt(val); //or just Number.parseInt
 if(!isNaN(num)) {
     sum += num;
 }

This blogpost sheds some more light on this check if a string is numeric in Javascript | Typescript & ES6


Just use isFinite

const number = "1";
if (isFinite(number)) {
    // do something
}

This function works for all test cases that i could find. It's also faster than:

function isNumeric (n) {
  if (!isNaN(parseFloat(n)) && isFinite(n) && !hasLeading0s(n)) {
    return true;
  }
  var _n = +n;
  return _n === Infinity || _n === -Infinity;
}

_x000D_
_x000D_
var isIntegerTest = /^\d+$/;_x000D_
var isDigitArray = [!0, !0, !0, !0, !0, !0, !0, !0, !0, !0];_x000D_
_x000D_
function hasLeading0s(s) {_x000D_
  return !(typeof s !== 'string' ||_x000D_
    s.length < 2 ||_x000D_
    s[0] !== '0' ||_x000D_
    !isDigitArray[s[1]] ||_x000D_
    isIntegerTest.test(s));_x000D_
}_x000D_
var isWhiteSpaceTest = /\s/;_x000D_
_x000D_
function fIsNaN(n) {_x000D_
  return !(n <= 0) && !(n > 0);_x000D_
}_x000D_
_x000D_
function isNumber(s) {_x000D_
  var t = typeof s;_x000D_
  if (t === 'number') {_x000D_
    return (s <= 0) || (s > 0);_x000D_
  } else if (t === 'string') {_x000D_
    var n = +s;_x000D_
    return !(fIsNaN(n) || hasLeading0s(s) || !(n !== 0 || !(s === '' || isWhiteSpaceTest.test(s))));_x000D_
  } else if (t === 'object') {_x000D_
    return !(!(s instanceof Number) || fIsNaN(+s));_x000D_
  }_x000D_
  return false;_x000D_
}_x000D_
_x000D_
function testRunner(IsNumeric) {_x000D_
  var total = 0;_x000D_
  var passed = 0;_x000D_
  var failedTests = [];_x000D_
_x000D_
  function test(value, result) {_x000D_
    total++;_x000D_
    if (IsNumeric(value) === result) {_x000D_
      passed++;_x000D_
    } else {_x000D_
      failedTests.push({_x000D_
        value: value,_x000D_
        expected: result_x000D_
      });_x000D_
    }_x000D_
  }_x000D_
  // true_x000D_
  test(0, true);_x000D_
  test(1, true);_x000D_
  test(-1, true);_x000D_
  test(Infinity, true);_x000D_
  test('Infinity', true);_x000D_
  test(-Infinity, true);_x000D_
  test('-Infinity', true);_x000D_
  test(1.1, true);_x000D_
  test(-0.12e-34, true);_x000D_
  test(8e5, true);_x000D_
  test('1', true);_x000D_
  test('0', true);_x000D_
  test('-1', true);_x000D_
  test('1.1', true);_x000D_
  test('11.112', true);_x000D_
  test('.1', true);_x000D_
  test('.12e34', true);_x000D_
  test('-.12e34', true);_x000D_
  test('.12e-34', true);_x000D_
  test('-.12e-34', true);_x000D_
  test('8e5', true);_x000D_
  test('0x89f', true);_x000D_
  test('00', true);_x000D_
  test('01', true);_x000D_
  test('10', true);_x000D_
  test('0e1', true);_x000D_
  test('0e01', true);_x000D_
  test('.0', true);_x000D_
  test('0.', true);_x000D_
  test('.0e1', true);_x000D_
  test('0.e1', true);_x000D_
  test('0.e00', true);_x000D_
  test('0xf', true);_x000D_
  test('0Xf', true);_x000D_
  test(Date.now(), true);_x000D_
  test(new Number(0), true);_x000D_
  test(new Number(1e3), true);_x000D_
  test(new Number(0.1234), true);_x000D_
  test(new Number(Infinity), true);_x000D_
  test(new Number(-Infinity), true);_x000D_
  // false_x000D_
  test('', false);_x000D_
  test(' ', false);_x000D_
  test(false, false);_x000D_
  test('false', false);_x000D_
  test(true, false);_x000D_
  test('true', false);_x000D_
  test('99,999', false);_x000D_
  test('#abcdef', false);_x000D_
  test('1.2.3', false);_x000D_
  test('blah', false);_x000D_
  test('\t\t', false);_x000D_
  test('\n\r', false);_x000D_
  test('\r', false);_x000D_
  test(NaN, false);_x000D_
  test('NaN', false);_x000D_
  test(null, false);_x000D_
  test('null', false);_x000D_
  test(new Date(), false);_x000D_
  test({}, false);_x000D_
  test([], false);_x000D_
  test(new Int8Array(), false);_x000D_
  test(new Uint8Array(), false);_x000D_
  test(new Uint8ClampedArray(), false);_x000D_
  test(new Int16Array(), false);_x000D_
  test(new Uint16Array(), false);_x000D_
  test(new Int32Array(), false);_x000D_
  test(new Uint32Array(), false);_x000D_
  test(new BigInt64Array(), false);_x000D_
  test(new BigUint64Array(), false);_x000D_
  test(new Float32Array(), false);_x000D_
  test(new Float64Array(), false);_x000D_
  test('.e0', false);_x000D_
  test('.', false);_x000D_
  test('00e1', false);_x000D_
  test('01e1', false);_x000D_
  test('00.0', false);_x000D_
  test('01.05', false);_x000D_
  test('00x0', false);_x000D_
  test(new Number(NaN), false);_x000D_
  test(new Number('abc'), false);_x000D_
  console.log('Passed ' + passed + ' of ' + total + ' tests.');_x000D_
  if (failedTests.length > 0) console.log({_x000D_
    failedTests: failedTests_x000D_
  });_x000D_
}_x000D_
testRunner(isNumber)
_x000D_
_x000D_
_x000D_