Validating number javascript

Rated 3.86/5 based on 619 customer reviews

I found the above worked unless the string began with 0xnn and then it would return it as numeric when it shouldn't have.I've posted in a comment below so the formatting is intact.

validating number javascript-56

This is a "standing-on-the-shoulders-of-giants" situation. function is Int(a) console.log(is Int('abcd')); // false console.log(is Int('123a')); // false console.log(is Int('1')); // true console.log(is Int('0')); // true console.log(is Int('-0')); // false console.log(is Int('01')); // false console.log(is Int('10')); // true console.log(is Int('-1234567890')); // true console.log(is Int(1234)); // true console.log(is Int('123.4')); // false console.log(is Int('')); // false // other types then string returns false console.log(is Int(5)); // false console.log(is Int(undefined)); // false console.log(is Int(null)); // false console.log(is Int('0x1')); // false console.log(is Int(Infinity)); // false % 1 === 0" worked unless the string began with 0xnn (like 0x10) and then it would return it as numeric when we didn't want it to.To get a string contains only numbers (0-9) we use a regular expression (/^[0-9] $/) which allows only numbers.Next, the match() method of the string object is used to match the said regular expression against the input value. To get a string contains only numbers (0-9) with a optional or - sign (e.g.So, unless you intend otherwise, it is safest to use parse Int(number, 10), specifying 10 as the radix explicitly.There are more ways than it seems to build a number (hex numbers in another comment are just one example), and there are many numbers that may not be considered valid (overflow the type, too precise, etc).

Leave a Reply