Simple ways to convert a string into a number

Simple ways to convert a string into a number

ยท

1 min read

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

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)

Plus (+) unary operator

const x = "5"

const num = +x

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 ๐Ÿ˜Š

ย