DEV Community

Jenuel Oras Ganawed
Jenuel Oras Ganawed

Posted on

Check String If its a number

When checking string if its a number, there are a lot of ways you can check a string if its a number. You can use regex, isNaN() function, or a plus operator, or parseInt.

But the best function that we can use is a function called Number().

The Number() function converts the argument to a number representing the object’s value. If it fails to convert the value to a number, it returns NaN.

We can use it with strings also to check whether a given string is a number or not.

console.log(Number('195')) // 195
console.log(Number('boo')) // Nan
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Number is cool, but it doesn't tell you whether something is a number. Au contraire: it will turn anything into a number, so tpeof Number(something) will always be "number" regardless of what something was before.

The easiest way to find out if a string is a number is to simply call isNaN on it and negate the output.

const isNumber = value => !isNaN(value)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
yigitt profile image
yigitt

how plus operator is used for conversion? afaik it combines strings.

Collapse
 
jenueldev profile image
Jenuel Oras Ganawed • Edited

The + operator returns the numeric value of the string, or NaN, if the string isn’t purely numeric characters.

example:

console.log(+'195'); // 195
console.log(+'boo'); // NaN
Enter fullscreen mode Exit fullscreen mode
Collapse
 
yigitt profile image
yigitt

Is there Any difference with other methods? ParseInt() and Number().

Thread Thread
 
jenueldev profile image
Jenuel Oras Ganawed • Edited

parseInt() is used for parsing a string to number.. It has similarities with Number() but parseInt() will extract a string to int. Number() on the other hand it converts string to number, and support different number format.

//example
let str = '34e10';

console.log(Number(str)); // 340000000000

console.log(parseInt(str)); // 34

Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
yigitt profile image
yigitt

Thank you Jenuel. Nice post.

Thread Thread
 
jenueldev profile image
Jenuel Oras Ganawed

thanks mate, :) happy to help :)