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

11 1

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 😊

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (1)

Collapse
 
msamgan profile image
Mohammed Samgan Khan

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay