Check if the character is a number?

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

A line is something like: "blabla, 120"

In this case, it will check if "0" is a number. How can I do that?

+84
javascript
Jan 20 '12 at 1:12
source share
22 answers

You can use isNaN() to check if this number is:

 var c = justPrices[i].substr(commapos + 2, 1); if (!isNaN(parseInt(c, 10))) { // Is a number } 

Or more verbose:

 if ('0123456789'.indexOf(c) !== -1) { // Is a number } 

And if you don't care about Internet Explorer:

 if ('0123456789'.includes(c)) { // Is a number } 
+106
Jan 20 '12 at 1:15
source share

You can use comparison operators to see if it is in the range of digits:

 var c = justPrices[i].substr(commapos+2,1); if (c >= '0' && c <= '9') { // it is a number } else { // it isn't } 
+50
Jan 20 '12 at 1:21
source share

you can use parseInt and check with isNaN

or if you want to work directly with your string, you can use regexp as follows:

 function is_numeric(str){ return /^\d+$/.test(str); } 
+29
Jan 20 2018-12-01T00:
source share

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

Here is the jQuery isNumeric implementation (in pure JavaScript) that works with full lines :

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

A comment on this feature reads:

// parseFloat NaNs - numeric false positives (null | true | false | "")
// ... but incorrectly interprets the string of initial numbers, especially hexadecimal literals ("0x ...")
// subtract the forces of infinity in NaN

I think we can believe that these guys spent a lot of time on this!

Commented source here . Super geek discussion here .

+17
Jan 12 '14 at 2:18
source share

You can use this:

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

Here I compared it with the accepted method: http://jsperf.com/isdigittest/5 . I did not expect much, so I was very surprised when I found out that the accepted method was much slower.

Interestingly, although the accepted method is rather the correct input (for example, "5") and slower for the wrong one (for example, "a"), my method is absolutely the opposite (fast for the wrong and slow for the correct).

However, in the worst case, my method is 2 times faster than the decision made for the correct input and more than 5 times faster for the incorrect input.

+15
Jun 09 '14 at 13:29
source share

I wonder why no one posted a solution like:

 var charCodeZero = "0".charCodeAt(0); var charCodeNine = "9".charCodeAt(0); function isDigitCode(n) { return(n >= charCodeZero && n <= charCodeNine); } 

with a call like:

 if (isDigitCode(justPrices[i].charCodeAt(commapos+2))) { ... // digit } else { ... // not a digit } 
+14
Jul 14 '16 at 9:43
source share

I think it’s very funny to come up with ways to solve this problem. Below are some of them. (All functions below assume that the argument is a single character. Go to n[0] to ensure it runs)

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 line:

 var str = ' 90ABcd#?:.+', char; for( char of str ) console.log( char, isCharDigit(char) ); 
+11
Sep 14 '15 at 19:35
source share

Simple function

 function isCharNumber(c){ return c >= '0' && c <= '9'; } 
+7
May 4 '18 at 21:27
source share

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.

+5
Jan 20 '12 at 1:27
source share

I suggest a simple regex.

If you are looking for only the last character in a 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 just check one character as input:

 var char = "0"; /^[0-9]$/.test(char); // true 
+3
04 Oct '18 at 17:36
source share
 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)); } } 

without strict modes:

 var num = 14; var textnum = '14'; var text = 'yo'; var nan = NaN; isNumber(num); isNumber(textnum); isNumber(text); isNumber(nan); true true false false 

strict mode output:

 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 
+1
Oct 06 '16 at 15:27
source share

Try:

 function is_numeric(str){ try { return isFinite(str) } catch(err) { return false } } 
+1
Mar 13 '18 at 10:17
source share
 function is_numeric(mixed_var) { return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var); } 

Source

0
May 6 '13 at 14:09
source share
 square = function(a) { if ((a * 0) == 0) { return a*a; } else { return "Enter a valid number."; } } 

Source

0
09 Oct '14 at 21:31
source share

You can try this (works in my case)

If you want to check if the first char is for an int string:

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

If you want to check if char is an int value:

 if (parseInt(YOUR_CHAR)) { alert("first char is int") } else { alert("first char is not int") } 
0
Oct 23 '14 at 11:22
source share

It works:

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 lines to see if they are numeric.

0
Jan 26 '16 at 10:54 on
source share
 var Is = { character: { number: (function() { // Only computed once var zero = "0".charCodeAt(0); var nine = "9".charCodeAt(0); return function(c) { return (c = c.charCodeAt(0)) >= zero && c <= nine; } })() } }; 
0
Sep 01 '17 at 11:33 on
source share

A simple solution using dynamic language type checking:

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

see test examples below

 function isNumber (string) { if(string === ' '.repeat(string.length)){ return false } return string - 0 === string * 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')) 

0
Jan 26 '19 at 20:08
source share

This feature works for all test cases that I could find. It is 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) 

0
Apr 23 '19 at 1:39 on
source share

The shortest solution:

 const isCharDigit = n => n < 10; 

You can also apply them:

 const isCharDigit = n => Boolean(++s); const isCharDigit = n => '/' < s && s < ':'; const isCharDigit = n => !!++s; 

if you want to check more than 1 chat you can use the following options

Regular expression:

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

Comparison:

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

Check if it is NaN

 const isDigit = n => !isNaN(n); 
0
Sep 16 '19 at 15:40
source share

As far as I know, the easiest way is to simply multiply by 1 :

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

Multiplying by one creates a number from any number line (since you only have one character, it will always be an integer from 0 to 9) and NaN for any other line.

0
Sep 25 '19 at 15:38
source share

Just use isFinite

 const number = "1"; if (isFinite(number)) { // do something } 
-one
Sep 05 '17 at 18:26
source share



All Articles