DEV Community

Cover image for 7 ways to convert a String to Number in JavaScript
Sanchithasr
Sanchithasr

Posted on • Edited on • Originally published at builtin.com

124 17

7 ways to convert a String to Number in JavaScript

1. Using parseInt()

parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned.
This method has a limitation though. If you parse the decimal number, it will be rounded off to the nearest integer value and that value is converted to string. One might need to use parseFloat() method for literal conversion.

myString = '129' 
console.log(parseInt(myString)) // expected result: 129

a = 12.22
console.log(parseInt(a)) // expected result: 12
Enter fullscreen mode Exit fullscreen mode

2. Using Number()

Number() can be used to convert JavaScript variables to numbers. We can use it to convert the string too number.
If the value cannot be converted to a number, NaN is returned.

Number("10");          // returns 10
Number(" 10  ");       // returns 10
Number("10.33");       // returns 10.33
Enter fullscreen mode Exit fullscreen mode

3. Using Unary Operator (+)

The unary plus operator (+) precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.

const x = 25;
const y = -25;
console.log(+x); // expected output: 25
console.log(+y); // expected output: -25
console.log(+''); // expected output: 0
Enter fullscreen mode Exit fullscreen mode

4. Using parseFloat()

parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned.

parseFloat("10");        // returns 10
parseFloat("10.33");     // returns 10.33
parseFloat("10 20 30");  // returns 10
parseFloat("10 years");  // returns 10
parseFloat("years 10");  // returns NaN
Enter fullscreen mode Exit fullscreen mode

5. Using Math.floor()

The Math.floor() function returns the largest integer less than or equal to a given number. This can be little tricky with decimal numbers since it will return the value of the nearest integer as Number.

str = '1222'
console.log(Math.floor(str)) // returns 1222

a = 12.22
Math.floor(a) // expected result: 12
Enter fullscreen mode Exit fullscreen mode

6. Multiply with number

Multiplying the string value with the 1 which won’t change the value and also it will be converted to number by default.

str = '2344'
console.log(str * 1) // expected result: 2344
Enter fullscreen mode Exit fullscreen mode

7. Double tilde (~~) Operator

We can use the double tilde operator to convert the string to number.

str = '1234'
console.log(~~str) // expected result: 1234
negStr = '-234'
console.log(~~negStr) // expected result: -234
Enter fullscreen mode Exit fullscreen mode

Here is the comparison of the ways mentioned performance wise. Comment below if you know more methods.
Thank You

Latest comments (21)

Collapse
 
tetile profile image
tetile

Cupcake 2048 is a delightful twist on the classic 2048 game, where you combine cupcakes to create even more delicious treats. It's a fun and addictive way to pass the time! You can play it 2048 cupcakes.

Enjoy the sweetness of 2048 cupcakes!

Collapse
 
leroydo profile image
mitchell maurice

The headline says: "If candy clicker parse the decimal number, it will be rounded off to the nearest integer value and that value is converted to string." I believe that the statement "That value is converted to a number" should be added.

Collapse
 
clevewren32 profile image
clevewren

Choosing the best method depends on your specific needs. If you need an integer, use parseInt. If you need a floating-point number, use parseFloat. Number() is a good general-purpose option, while the unary plus operator and multiplication by 1 are convenient for quick conversions but might have unexpected behavior. Remember to handle potential NaN results for robustness. Slope 3 is so addictive! I can't stop trying to beat my high score

Collapse
 
nathan-wells profile image
Nathan wells

I like the Using parseInt() method for generating numbers.

mbox converter

Collapse
 
writing2 profile image
ESSAY WRITING

Thanks very helpful 👍👌

Collapse
 
fitgag profile image
FitGAG

This is a really helpful article! As a beginner in JavaScript, I often find myself struggling with converting strings to numbers. It's great to see all these different methods laid out with examples for each one. I especially appreciated the explanation of the parseFloat() function and the caution against using the unary plus operator on strings that could be mistaken for numbers. Thank you for sharing! FitGAG

Collapse
 
adammagestore profile image
adam pham

For the string that includes comma (VD: '1,234.44'), you can use parseNumber function to avoid the further bug

Collapse
 
sigitnur profile image
Sigit

nice info. some time forget about this and using lib js

Collapse
 
himanshupal0001 profile image
Himanshupal0001

Noice

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more