How to Convert a String to a Number in JavaScript
h
MrEconomical (2194)

what is this tutorial

As you clicked on this post, you may be thinking, "I already know how to convert a string to a number. It's super easy. Why does this post even exist?" Converting a string to a number is one of the most simple and widely used tasks in JavaScript. It even has a built-in function, parseInt(). That's all there is to it, right? Wrong! As we will see later in this post, there are far more ways to convert a string to a number, some more cursed than others. In this tutorial, we will take a journey from some of the most innocent and simple operators to the deep pits of type conversion hell in JavaScript. Stay tuned to learn some quirks and oddities about how the language works!

Let's start off simple

Method 1: parseInt()

Probably one of the most widely used functions, parseInt() allows us to quickly turns numbers to integers. Take this example: parseInt("5") ⇒ 5 (NOTE: I will use to denote a return value of a statement). Seems simple enough. What happens when we try some other values?

parseInt("55.5") ⇒ 55
parseInt("2e") ⇒ 2
parseInt("g") ⇒ NaN

How does this make any sense? The parseInt() function actually reads the string from left to right, with whitespace at the beginning and ends ignored. It will keep reading the string as long as the portion defines a whole number, and any unexpected character will cause it to return immediately. This explains why 2e evaluates to 2. If no value can be read, NaN is returned.

Method 2: parseFloat()

parseFloat() is very similar to its sister function parseInt() except it will accept decimals: parseFloat("55.5") ⇒ 55.5. Like before, parseFloat() reads the string from left to right and also will return after reaching an unexpected character.

Method 3: Number()

The above two methods use parsing of a string by reading the characters. The Number() method casts the type of the string to an integer. Number("5") ⇒ 5 This method is more strict with any strings containing invalid characters returning NaN since the entire string is typecasted:

Number("55.5") ⇒ 55.5
Number("2e") ⇒ NaN
Number("g") ⇒ NaN

The methods listed above are fairly standard, now we will get into some of the more cursed ways to convert strings to numbers.

Method 4: Math functions

Surprisingly, common Math functions like Math.floor() or Math.round() can be used to convert strings to integers. Math.floor("5") ⇒ 5". Why is this? The Math function tries to be convenient for the programmer and automatically converts string inputs into numbers, then evaluates the result. This means we can use any Math function we want, although this method is not advised. Like Number(), the entire string must be a valid number or NaN will be returned:

Math.floor("2e") ⇒ NaN
Math.floor("g") ⇒ NaN

Method 5: Unary +

The unary + is what real gamers use a very interesting way to convert a string to a number. It looks something like this: +"5" ⇒ 5. This was actually built into the language and not many people have heard about this method. It is actually one of the fastest ways to convert a string to a number, and all sorts of values work, but the entire string must be a number once again:

+"55.5" ⇒ 55.5
+"2tw" ⇒ NaN

In fact, the unary + boolean values. It tries to convert anything it can:

+true ⇒ 1
+false ⇒ 0

The unary negation operation also works, but it converts the number to its opposite (* -1) and is hardly ever seen because why would you ever need to do that?

Method 6: Multiplication by 1

As you were reading this, you probably thought "What? How can I multiply a string by one?" It turns out that JavaScript is so weakly typed that it pretty much converts everything it can to be of a compatible type. Exploiting this, we can "multiply a string by one" to convert it to be a number: "5" * 1 ⇒ 5. This also works with dividing by one, and you might think it would work with all arithmetic operators but adding zero does not work! That's because seeing a string, JavaScript actually converts the 0 to a string and adds it on the end: "5" + 0 ⇒ "50". However, subtracting zero does work.

Method 7: Bitwise Operators

Using a bitwise operator on a string like | or & will convert it to a number: "5" | 0 ⇒ 5. Again, JavaScript wants all its types to be in order so it automatically converts strings into numbers before executing bitwise operations. With this method, decimals will not work, only integer values get returned: "12.6" | 0 ⇒ 12. Any bitwise operator can be used as long as the value is maintained. These include ~~, | 0, >> 0, and so on. One thing to note is that any values over 32 bits will overflow and wrap. Additionally, instead of evaluating to NaN, invalid values will evaluate to 0: "e" >> 0 ⇒ 0

javascript sucks (or does it?)

I hope you enjoyed this tutorial and learned something you didn't know about JavaScript! It's weak typing and automatic conversions certainly do open up the possibility for lots of cursed operations. However, this doesn't necessarily mean as a language JavaScript is bad although some may say so, but rather all of the conversions usually make it easier to use, and only in a few cases act unnaturally, like those mentioned above.

Thanks for reading, and E

You are viewing a single comment. View All