(Built-in) way in JavaScript to check if a string is a valid number (Built-in) way in JavaScript to check if a string is a valid number javascript javascript

(Built-in) way in JavaScript to check if a string is a valid number


2nd October 2020: note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point ".":

function isNumeric(str) {  if (typeof str != "string") return false // we only process strings!    return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...         !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail}

To check if a variable (including a string) is a number, check if it is not a number:

This works regardless of whether the variable content is a string or number.

isNaN(num)         // returns true if the variable does NOT contain a valid number

Examples

isNaN(123)         // falseisNaN('123')       // falseisNaN('1e10000')   // false (This translates to Infinity, which is a number)isNaN('foo')       // trueisNaN('10px')      // trueisNaN('')          // falseisNaN(' ')         // falseisNaN(false)       // false

Of course, you can negate this if you need to. For example, to implement the IsNumeric example you gave:

function isNumeric(num){  return !isNaN(num)}

To convert a string containing a number into a number:

Only works if the string only contains numeric characters, else it returns NaN.

+num               // returns the numeric value of the string, or NaN                    // if the string isn't purely numeric characters

Examples

+'12'              // 12+'12.'             // 12+'12..'            // NaN+'.12'             // 0.12+'..12'            // NaN+'foo'             // NaN+'12px'            // NaN

To convert a string loosely to a number

Useful for converting '12px' to 12, for example:

parseInt(num)      // extracts a numeric value from the                    // start of the string, or NaN.

Examples

parseInt('12')     // 12parseInt('aaa')    // NaNparseInt('12px')   // 12parseInt('foo2')   // NaN      These last two may be differentparseInt('12a5')   // 12       from what you expected to see. 

Floats

Bear in mind that, unlike +num, parseInt (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use parseInt() because of this behaviour, you're probably better off using another method instead):

+'12.345'          // 12.345parseInt(12.345)   // 12parseInt('12.345') // 12

Empty strings

Empty strings may be a little counter-intuitive. +num converts empty strings or strings with spaces to zero, and isNaN() assumes the same:

+''                // 0+'   '             // 0isNaN('')          // falseisNaN('   ')       // false

But parseInt() does not agree:

parseInt('')       // NaNparseInt('   ')    // NaN


If you're just trying to check if a string is a whole number (no decimal places), regex is a good way to go. Other methods such as isNaN are too complicated for something so simple.

function isNumeric(value) {    return /^-?\d+$/.test(value);}console.log(isNumeric('abcd'));         // falseconsole.log(isNumeric('123a'));         // falseconsole.log(isNumeric('1'));            // trueconsole.log(isNumeric('1234567890'));   // trueconsole.log(isNumeric('-23'));          // trueconsole.log(isNumeric(1234));           // trueconsole.log(isNumeric(1234n));          // trueconsole.log(isNumeric('123.4'));        // falseconsole.log(isNumeric(''));             // falseconsole.log(isNumeric(undefined));      // falseconsole.log(isNumeric(null));           // false

To only allow positive whole numbers use this:

function isNumeric(value) {    return /^\d+$/.test(value);}console.log(isNumeric('123'));          // trueconsole.log(isNumeric('-23'));          // false


And you could go the RegExp-way:

var num = "987238";if(num.match(/^-?\d+$/)){  //valid integer (positive or negative)}else if(num.match(/^\d+\.\d+$/)){  //valid float}else{  //not valid number}