(photo by Volkan Olmez on Unsplash)
Read on Medium:
The Best Way to Convert a String to a Number in JavaScript | by Andrew Koenig-Bautista | Better Programming | Medium
Andrew Koenig-Bautista ・ ・ 4 min read
Medium
As you probably already know, there are a variety of ways to convert a string to an integer in JavaScript. However, it's up for debate as to which method is the "best" method available to developers. Let's take a look at some options.
parseInt()
parseInt(string, radix)
We begin with parseInt() which takes two arguments, a string and a radix. The function returns an integer parsed from the given string.
If the first argument is not a string, it is converted to one automatically using ToString(). Either way, any leading whitespace is ignored.
The parseInt() method starts at position 0 and determines if the character found there can be converted into a valid number. If not, the method returns NaN and stops. Here is an example:
const str = "What's funnier than 24?",
console.log(parseInt(str)) // NaN
The output would be NaN, in spite of the string containing a number.
If the character at position 0 is valid, the method moves on and carries out the same test. This goes on until parseInt() encounters an invalid number, at which point it will convert the current string into a number.
console.log(parseInt("24haha25")) // 24
This would return 24 as it would stop parsing at haha, which is NaN.
MDN suggests that when using parseInt() you should "Always specify a radix to avoid.. unreliable behavior." This is because pre-ECMAScript 5, parseInt() used the octal radix (8) as default if a string began with "0". As of ECMAScript 5, the default is the decimal radix (10):
If radix is undefined or 0, it is assumed to be 10 except when the number begins with the character pairs 0x or 0X, in which case a radix of 16 is assumed.
parseFloat()
parseFloat(string)
parseFloat() is quite similar to parseInt(), with two main differences.
First, unlike parseInt(), parseFloat() does not take a radix as an argument. This means that string must represent a floating-point number in decimal form (radix 10), not octal (radix 8) or hexadecimal (radix 6).
Second, when using parseFloat() a decimal point is a valid character, but only the first time it is encountered. If a second decimal point is reached, the method will stop parsing at that position.
console.log(parseFloat("3.141.59")) // 3.141
Otherwise, the other behaviors of parseInt() are found here as well:
-Only the first number in the string is returned
-Leading and trailing whitespace is allowed and ignored
-If the first character is not a valid number, NaN is returned
Number()
Number(value)
The parse functions and Number() are largely interchangeable. Number() can handle one decimal, but will also be thrown off by more than one decimal point. Leading and trailing whitespace are still accepted and ignored.
There are a few differences. The parse methods, as the name suggests, attempt to parse through a string piece by piece as they convert it, Number() attempts to convert the entire string argument into a number, all at once.
const str = '123abc';
Number(str); // NaN (attempts to convert entire string, cannot)
parseInt(s); // 123 (stops as soon as it hits `a`)
Number() is the JavaScript Number constructor called as a function, which performs a type conversion. It attempts to convert any value to a number:
-false becomes 0, true becomes 1
-null becomes 0, undefined becomes NaN
-Empty string '' becomes 0, non-numerical strings become NaN
-Number('') gives 0; parseInt('') gives NaN
Here's a Number() overview from w3schools:
Unary + Operator
You may or may not be aware of the ability of the + unary operator to convert a string to a number in JavaScript. For example:
+"123" // 123
+"123.456" // 123.456
+"123.456.789" // NaN
+"I'm a number" // NaN
As far as I know, using the unary + operator this way exactly mimics the behavior of Number() without any exceptions. So why use Number() at all?
Some people see the + operator as a form of syntactic sugar because it can be used to abbreviate the parse functions or Number() functionality.
However, less code does not always equal more concise code. Clarity should be taken into consideration when making decisions about shortcuts like this.
Not everyone may be aware of this behavior, which could lead to confusion for someone reading your code, whereas parseInt() is clear and concise.
In my opinion, generally speaking, you should use code that describes what it does instead of code that uses a side effect of a non-operation
Multiply by 1
Another shortcut of sorts, if you know the string that you are seeking to convert is a number, you can multiply it by one to convert it:
"123"*1 // 123
"123.456"*1 // 123.456
"123.456.789"*1 // NaN
"I'm a number"*1 // NaN
Again, this method behaves the same as Number() and I've seen it touted as being the fastest conversion method. However, my previous concerns about the usefulness of such syntactic sugar apply here as well.
So What Method Is Best?
I ask this genuinely, dear readers! Now that we've covered some (but not all) options here, I would love to hear your opinions on what method (or methods) you believe to be best (and why).
I'm sure many of you are much more knowledgable than I am about performance times, although the performance for operators and functions changes with the optimization of the JavaScript engine in browsers.
I hope to read some helpful and healthy debates, and if nothing else I hope this serves a good review and maybe you even learned something new.
Thanks for reading!
Top comments (1)
Nice article. By your explanation, I'll use regex to identify if the string has only numbers then I'll convert it to what I need with
parseInt()
orparseFloat()
, depending again on what I need.Sorry I complicate things XD