167

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?

lisovaccaro
  • 32,502
  • 98
  • 258
  • 410
  • 1
    possible duplicate to [here](http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric) – cctan Jan 20 '12 at 01:14
  • 1
    @cctan It's not a duplicate. That question is about checking a string, this is about checking a character. – jackocnr May 27 '18 at 09:19
  • Possible duplicate of [Validate decimal numbers in JavaScript - IsNumeric()](https://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric) – Stephan Weinhold Mar 18 '19 at 13:01

28 Answers28

121

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
}
GregL
  • 37,147
  • 8
  • 62
  • 67
79

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);
}
Yaron U.
  • 7,681
  • 3
  • 31
  • 45
  • 12
    Or even simpler if we only need to check a single character: `function is_numeric_char(c) { return /\d/.test(c); }` – jackocnr Apr 01 '17 at 15:41
  • 9
    @jackocnr your test will also return true for strings that contains more than just a char (e.g. `is_numeric_char("foo1bar") == true`). if you want to check for a numeric char `/^\d$/.test(c)` would be a better solution. but anyway, it wasn't the question :) – Yaron U. Apr 04 '17 at 16:12
  • You can also use typeof like: `typeof parseInt(char, 10) === 'number'` – jaquinocode Mar 06 '22 at 06:54
40

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.

jackocnr
  • 17,068
  • 10
  • 54
  • 63
  • 2
    This works, but it is an overkill for digit-only check (it works with multi-digit numbers). My solution may not be as clear, but is much faster than this. – user2486570 Jul 19 '14 at 16:36
38

Simple function

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

If you want to ensure c is really a single character

function isCharNumber(c) {
  return typeof c === 'string' && c.length == 1 && c >= '0' && c <= '9';
}
optical
  • 161
  • 7
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
  • 1
    This works in languages like C if `c` has type char, but in JS the function will return true for any string that starts with a digit. However if you add something like `c.length == 1 &&` just after the return keyword, I think it's a good solution. – optical Mar 16 '23 at 18:52
  • @optical answer updated accordingly – João Pimentel Ferreira Mar 17 '23 at 07:41
  • 1
    I think your second version is still missing a verification, because it would return true for the input `0a-!` for example. I submitted an edit that checks if it's a single character. – optical Mar 19 '23 at 16:30
31

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
}
Marian
  • 7,402
  • 2
  • 22
  • 34
19

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.

user2486570
  • 902
  • 8
  • 14
  • 5
    I love this answer! Maybe optimize it to: `!!([!0, !0, !0, !0, !0, !0, !0, !0, !0, !0][n]);` It has great WTF potential and works quite well (fails for `007`). – Jonathan Sep 15 '15 at 19:20
  • @Jonathan - see my [answer](http://stackoverflow.com/a/32572539/104380), method #4 – vsync Mar 30 '16 at 11:26
  • 9
    According to this 'solution', `"length"` (and other attributes found on arrays) are digits :P – Shadow Dec 14 '17 at 04:50
13

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) );
vsync
  • 118,978
  • 58
  • 307
  • 400
6

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
zenslug
  • 61
  • 1
  • 1
6

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

If you are testing single characters, then:

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

['e','0'].forEach(c => console.log(
  `isDigit("${c}") : ${isDigit(c)}`)
);

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

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Why make isDigit a self-executing function's return function, why not just make it equal to a regular function? – Artur Feb 11 '23 at 18:28
  • 1
    @Artur—to keep the regular expression in a closure so it doesn't have to be created every time the function is run. Premature optimisation? Perhaps. – RobG Feb 12 '23 at 22:33
3
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;
            }
        })()
    }
};
mjs
  • 21,431
  • 31
  • 118
  • 200
3

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

cptdanko
  • 812
  • 2
  • 13
  • 22
3

Here is a simple function that does it.

function is_number(char) {
    return !isNaN(parseInt(char));
}

Returns: true, false
Stan S.
  • 237
  • 7
  • 22
1
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
buræquete
  • 14,226
  • 4
  • 44
  • 89
Banning Stuckey
  • 565
  • 1
  • 6
  • 11
1

Try:

function is_numeric(str){
        try {
           return isFinite(str)
        }
        catch(err) {
            return false
        }
    }
sg7
  • 6,108
  • 2
  • 32
  • 40
Insp
  • 11
  • 1
1

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

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'))
Mechanic
  • 5,015
  • 4
  • 15
  • 38
1

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.

1234ru
  • 692
  • 8
  • 16
1

I am using this:

const isNumber = (str) => (
    str.length === str.trim().length 
    && str.length > 0
    && Number(str) >= 0
)

It works for strings or single characters.

1

modifying this answer to be little more convenient and limiting to chars(and not string):

const charCodeZero = "0".charCodeAt(0);
const charCodeNine = "9".charCodeAt(0);
function isDigit(s:string) {
    return s.length==1&& s.charCodeAt(0) >= charCodeZero && s.charCodeAt(0) <= charCodeNine;
}

console.log(isDigit('4'))   //true
console.log(isDigit('4s'))  //false
console.log(isDigit('s'))   //false

Eliav Louski
  • 3,593
  • 2
  • 28
  • 52
0
function is_numeric(mixed_var) {
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') &&
        mixed_var !== '' && !isNaN(mixed_var);
}

Source code

buræquete
  • 14,226
  • 4
  • 44
  • 89
Alexander Serkin
  • 1,679
  • 1
  • 12
  • 11
0
square = function(a) {
    if ((a * 0) == 0) {
        return a*a;
    } else {
        return "Enter a valid number.";
    }
}

Source

buræquete
  • 14,226
  • 4
  • 44
  • 89
Lourayad
  • 9
  • 1
0

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")
}
buræquete
  • 14,226
  • 4
  • 44
  • 89
  • `if (parseInt(YOUR_CHAR))` would not be truish when the character is 0 though :) at least you have to do `if (parseInt(YOUR_CHAR) + 1) ` or better compare to `NaN` => `if (parseInt(YOUR_CHAR) !== NaN)` – mgoetzke Nov 25 '21 at 08:32
0

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.

Matthew Layton
  • 39,871
  • 52
  • 185
  • 313
0

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

var isIntegerTest = /^\d+$/;
var isDigitArray = [!0, !0, !0, !0, !0, !0, !0, !0, !0, !0];

function hasLeading0s(s) {
  return !(typeof s !== 'string' ||
    s.length < 2 ||
    s[0] !== '0' ||
    !isDigitArray[s[1]] ||
    isIntegerTest.test(s));
}
var isWhiteSpaceTest = /\s/;

function fIsNaN(n) {
  return !(n <= 0) && !(n > 0);
}

function isNumber(s) {
  var t = typeof s;
  if (t === 'number') {
    return (s <= 0) || (s > 0);
  } else if (t === 'string') {
    var n = +s;
    return !(fIsNaN(n) || hasLeading0s(s) || !(n !== 0 || !(s === '' || isWhiteSpaceTest.test(s))));
  } else if (t === 'object') {
    return !(!(s instanceof Number) || fIsNaN(+s));
  }
  return false;
}

function testRunner(IsNumeric) {
  var total = 0;
  var passed = 0;
  var failedTests = [];

  function test(value, result) {
    total++;
    if (IsNumeric(value) === result) {
      passed++;
    } else {
      failedTests.push({
        value: value,
        expected: result
      });
    }
  }
  // true
  test(0, true);
  test(1, true);
  test(-1, true);
  test(Infinity, true);
  test('Infinity', true);
  test(-Infinity, true);
  test('-Infinity', true);
  test(1.1, true);
  test(-0.12e-34, true);
  test(8e5, true);
  test('1', true);
  test('0', true);
  test('-1', true);
  test('1.1', true);
  test('11.112', true);
  test('.1', true);
  test('.12e34', true);
  test('-.12e34', true);
  test('.12e-34', true);
  test('-.12e-34', true);
  test('8e5', true);
  test('0x89f', true);
  test('00', true);
  test('01', true);
  test('10', true);
  test('0e1', true);
  test('0e01', true);
  test('.0', true);
  test('0.', true);
  test('.0e1', true);
  test('0.e1', true);
  test('0.e00', true);
  test('0xf', true);
  test('0Xf', true);
  test(Date.now(), true);
  test(new Number(0), true);
  test(new Number(1e3), true);
  test(new Number(0.1234), true);
  test(new Number(Infinity), true);
  test(new Number(-Infinity), true);
  // false
  test('', false);
  test(' ', false);
  test(false, false);
  test('false', false);
  test(true, false);
  test('true', false);
  test('99,999', false);
  test('#abcdef', false);
  test('1.2.3', false);
  test('blah', false);
  test('\t\t', false);
  test('\n\r', false);
  test('\r', false);
  test(NaN, false);
  test('NaN', false);
  test(null, false);
  test('null', false);
  test(new Date(), false);
  test({}, false);
  test([], false);
  test(new Int8Array(), false);
  test(new Uint8Array(), false);
  test(new Uint8ClampedArray(), false);
  test(new Int16Array(), false);
  test(new Uint16Array(), false);
  test(new Int32Array(), false);
  test(new Uint32Array(), false);
  test(new BigInt64Array(), false);
  test(new BigUint64Array(), false);
  test(new Float32Array(), false);
  test(new Float64Array(), false);
  test('.e0', false);
  test('.', false);
  test('00e1', false);
  test('01e1', false);
  test('00.0', false);
  test('01.05', false);
  test('00x0', false);
  test(new Number(NaN), false);
  test(new Number('abc'), false);
  console.log('Passed ' + passed + ' of ' + total + ' tests.');
  if (failedTests.length > 0) console.log({
    failedTests: failedTests
  });
}
testRunner(isNumber)
c7x43t
  • 274
  • 2
  • 6
0

Use simple regex solution to check only one char:

function isDigit(chr) {
      return  chr.match(/[0-9]/i);
}
burak isik
  • 395
  • 5
  • 6
  • this will not return a boolean value; wrap the returned value with Boolen. Also, it will return a match for a chr like "1asd", so you need to modify your regex to only one character, so the final returned value should be: Boolean(this.match(/^[0-9]$/i)) – Elyasaf755 Aug 09 '22 at 06:27
  • @Elyasaf755 I did not make any explanation about whether the function returns a boolean value. You can use the function like that if(isDigit('5')) { ... } – burak isik Aug 12 '22 at 09:01
  • 1
    Naming a function "isSomething" while it's not returning a boolean value is VERY confusing. Also, even the way you explained in the comments how this function should be used is incorrect as I already explained that the function will have a truthy value for the parameter "1asd", meaning that the following code will print "I AM A DIGIT" to console, which is extremely incorrect, try it: if (isDigit("asd123QWERT")) console.log("I AM A DIGIT") – Elyasaf755 Aug 12 '22 at 15:46
  • Why do you pass a string instead of a char as a parameter? The main purpose of the function is to return whether the character given as a parameter is a digit or not. On the other hand, Developer who will use the code snippet can add extra control to the function to avoid a sad path. – burak isik Aug 15 '22 at 09:08
0

let ch = '6'; // or any other string that has integer value

Simple function that can be used : !isNaN(ch - '0')

  • Your answer could be improved with additional supporting information. Please [edit](https://stackoverflow.com/posts/72517845/edit) to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the [help center](https://stackoverflow.com/help/how-to-answer). – Ethan Jun 07 '22 at 20:34
0

Try using isNAN

generally:

isNAN(char)

examples:

let isNum = !isNAN('5')  // true
let isNum = !isNAN('a')  // false
Matt
  • 33,328
  • 25
  • 83
  • 97
-1

Just use isFinite

const number = "1";
if (isFinite(number)) {
    // do something
}
Gibolt
  • 42,564
  • 15
  • 187
  • 127