4 Easy Ways to Covert a JavaScript String to a Number

4 Easy Ways to Covert a JavaScript String to a Number

And How to Remove the trailing Zeros on a Floating Point Number

ยท

3 min read

Having to check if a string is a number, and then type convert it to a number, comes up a lot when coding in JavaScript. If you're done more than 5 leetcode problems, then you know what I'm talking about! ๐Ÿ˜…

It's also super useful when coding applications too. The classic example is the calculator app, where you're taking in input values from the users as strings, and you need to verify that these values are valid numbers (or operators).

How do you check if a String is a Number?

There's a JavaScript method with a funny name called isNaN(str). Which translates to "is Not a Number". It returns true if str is not a number, and false if it IS a number.

If we use !isNaN(str) we get true if str is a number....

!isNaN('๐Ÿ‘พ123') // => false
!isNaN('๐Ÿ˜บ') // => false
!isNaN('456') // => true

// works for floats too
!isNaN('-2.5') // => true

Great, now how do I Convert the String to a Number?

There are 4 ways to type convert a string to a number (if it is a number).

WARNING: If the string is NOT a number, do NOT attempt to convert it to a number, because you'll either get NaN back or sometimes 0 if you convert an empty string or space to a number. Good luck finding that bug in your code!** ๐Ÿคฌ

So ALWAYS check if it's a number using !isNaN(str) FIRST.

Got it? Cool! Let's type convert:

// for integers
+'456' // => 456
parseInt('456') // => 456 
Number('456') // => 456

// for floating point numbers
+'-2.600' // => -2.6
parseFloat('-2.600') // => -2.6 
Number('-2.600') // => -2.6

Note that parseInt(...) ONLY works for integers, if you give it a float it will cut off everything after the ., so parseInt('-2.6') becomes -2.

How to Remove Trailing (and Leading) Zeros from a Floating Point Number

Notice I added some zeros at the end of -2.6 I did that to illustrate something cool: by type converting a string to a float, all unnecessary floating point zeros that come after AND before will be removed.

This really comes in handy.

For example:

+'-000002.600' // => -2.6

Related trick: if you have a float with a lot of trailing zeros you want to get rid of, just convert it to a string THEN back to a number with +:

const annoyingNumber = 1.230000000000;

const cleanNumber = +annoyingNumber.toString();

console.log(cleanNumber); // => 1.23

๐Ÿ˜Ž

My Favorite Option for Converting from String to Number in JavaScript?

Hands down, my favorite is the + operator. It's just one character long, gotta love it! ๐Ÿ˜ป

What's your favorite?

Did you find this article valuable?

Support Amit Mehta by becoming a sponsor. Any amount is appreciated!

ย