DEV Community

Cover image for Simple ways to convert a string into a number
Dhairya Shah
Dhairya Shah

Posted on • Originally published at codewithsnowbit.hashnode.dev

Simple ways to convert a string into a number

Hello Folks 👋

What's up friends, this is SnowBit here. I am a young passionate and self-taught front-end web developer and have an intention to become a successful developer.

Today, I am here with a basic topic for my beginner friends and javascript revisers. Happy Reading!


In this article, I will be discussing a few methods to convert a string into a number.

parseInt()

const x = "5"

parseInt(x) // 5
Enter fullscreen mode Exit fullscreen mode

You can easily convert a string to a number with parseInt(). If you pass any word or a letter in parseInt() then it will return Nan - Not a Number

Number()

In JavaScript, the Number() method converts the value to a number and if the value failed to convert then it will return NaN.

const x = "5"

Number(x)
Enter fullscreen mode Exit fullscreen mode

Plus (+) unary operator

const x = "5"

const num = +x
Enter fullscreen mode Exit fullscreen mode

Using the + operator alone before an element indicates a math operation and tries to convert the element to a number, and if it fails to do - it will return NaN


Thank you for reading, have a nice day!
Your appreciation is my motivation 😊

Top comments (1)

Collapse
 
msamgan profile image
Mohammed Samgan Khan

yaa, try soing that in php with number like 1,200