133

Any number, it's number. String looks like a number, it's number. Everything else, it goes NaN.

'a' => NaN
'1' => 1
1 => 1
5
  • What is fastest is dependant on the optimizations in a given implementation at a given time. There's no objectively "fastest" way. Commented Oct 12, 2012 at 15:48
  • 2
    What should be done with '1a' string? With ' 1' one? In other words, why most common methods to do that (Number(x) and parseInt(x, 10)) are not sufficient to you? Commented Oct 12, 2012 at 15:50
  • A previous jsperf test: jsperf.com/converting-string-to-int/3 Commented Oct 12, 2012 at 15:50
  • here a good performance comparison of the different methods: jsben.ch/#/NnBKM Commented Oct 25, 2016 at 8:12
  • See Also: How to convert a string to an integer in JavaScript? Commented Oct 12, 2021 at 19:41

10 Answers 10

207

There are 4 ways to do it as far as I know.

Number(x);
parseInt(x, 10);
parseFloat(x);
+x;

By this quick test I made, it actually depends on browsers.

https://jsben.ch/NnBKM

Implicit marked the fastest on 3 browsers, but it makes the code hard to read… So choose whatever you feel like it!

Sign up to request clarification or add additional context in comments.

5 Comments

Interestingly Google Analytics (the part you paste into your website) uses 1* for date-to-number conversion, which is similar to the + above. i.e. 1*new Date() rather than +new Date(). Possibly it's more readable?
I think 1* is preferred because it is less error prone. A unwanted dangling variable before +1 is not a parsing error. It is a trick similar to using if (MYCONSTANT == myvar) in C.
@beatak - Current optimizations seem to favor native methods as opposed to implicit conversion. I'm getting fastest for Number() in Chrome 37.0.2062.124 on Windows Server 2008 R2 / 7 and ParseInt() in Firefox 30.0 with implicit being the slowest for both. Also, you might consider including string literal floats in the test for general comparison. My guess is that it may change the order in some cases because string to float conversion is generally slower than string to int conversion. The way the test is now, it's getting away with a string to int conversion when Number() is used.
Chrome 61.0.3163. Number() is fastest of all.
I just compared Number() to ~~ (just a few runs on jsben.ch), and Number() won, though sometimes it was nearly even.
72

There are at least 5 ways to do this:

If you want to convert to integers only, another fast (and short) way is the double-bitwise not (i.e. using two tilde characters):

e.g.

~~x;

Reference: http://james.padolsey.com/cool-stuff/double-bitwise-not/

The 5 common ways I know so far to convert a string to a number all have their differences (there are more bitwise operators that work, but they all give the same result as ~~). This JSFiddle shows the different results you can expect in the debug console: http://jsfiddle.net/TrueBlueAussie/j7x0q0e3/22/

var values = ["123",
          undefined,
          "not a number",
          "123.45",
          "1234 error",
          "2147483648",
          "4999999999"
          ];

for (var i = 0; i < values.length; i++){
    var x = values[i];

    console.log(x);
    console.log(" Number(x) = " + Number(x));
    console.log(" parseInt(x, 10) = " + parseInt(x, 10));
    console.log(" parseFloat(x) = " + parseFloat(x));
    console.log(" +x = " + +x);
    console.log(" ~~x = " + ~~x);
}

Debug console:

123
  Number(x) = 123
  parseInt(x, 10) = 123
  parseFloat(x) = 123
  +x = 123
  ~~x = 123
undefined
  Number(x) = NaN
  parseInt(x, 10) = NaN
  parseFloat(x) = NaN
  +x = NaN
  ~~x = 0
null
  Number(x) = 0
  parseInt(x, 10) = NaN
  parseFloat(x) = NaN
  +x = 0
  ~~x = 0
"not a number"
  Number(x) = NaN
  parseInt(x, 10) = NaN
  parseFloat(x) = NaN
  +x = NaN
  ~~x = 0
123.45
  Number(x) = 123.45
  parseInt(x, 10) = 123
  parseFloat(x) = 123.45
  +x = 123.45
  ~~x = 123
1234 error
  Number(x) = NaN
  parseInt(x, 10) = 1234
  parseFloat(x) = 1234
  +x = NaN
  ~~x = 0
2147483648
  Number(x) = 2147483648
  parseInt(x, 10) = 2147483648
  parseFloat(x) = 2147483648
  +x = 2147483648
  ~~x = -2147483648
4999999999
  Number(x) = 4999999999
  parseInt(x, 10) = 4999999999
  parseFloat(x) = 4999999999
  +x = 4999999999
  ~~x = 705032703

The ~~x version results in a number in "more" cases, where others often result in undefined, but it fails for invalid input (e.g. it will return 0 if the string contains non-number characters after a valid number).

Overflow

Please note: Integer overflow and/or bit truncation can occur with ~~, but not the other conversions. While it is unusual to be entering such large values, you need to be aware of this. Example updated to include much larger values.

Some Perf tests indicate that the standard parseInt and parseFloat functions are actually the fastest options, presumably highly optimised by browsers, but it all depends on your requirement as all options are fast enough: http://jsperf.com/best-of-string-to-number-conversion/37

This all depends on how the perf tests are configured as some show parseInt/parseFloat to be much slower.

My theory is:

  • Lies
  • Darn lines
  • Statistics
  • JSPerf results :)

3 Comments

Be really careful for numbers larger than 2147483647. eg: ~~4294967296 returns 0.
@JosephGoh: When I get a chance I will extend the results to include int range overflow. Generally, if the numbers are that big you have a very special interface going on so would need to be aware of overflow. Cheers
@JosephGoh: Interestingly, in Chrome, you don't get 0's, you get negative numbers past the signed max value. Then it appears to simply drop the extra bits when you exceed unsigned int max value. e.g. "4999999999" => 705032703
9

Prefix the string with the + operator.

console.log(+'a') // NaN
console.log(+'1') // 1
console.log(+1) // 1

Comments

8

A fast way to convert strings to an integer is to use a bitwise or, like so:

x | 0

While it depends on how it is implemented, in theory it should be relatively fast (at least as fast as +x) since it will first cast x to a number and then perform a very efficient or.

2 Comments

Yes, but I believe this technique truncate large integers, that is pretty bad. To be noted, I can also be used instead of Math.floor(), but with same issue.
Here's a jsperf of various bitwise operators in conjunction with the methods in the first answer. I randomized the order because I found that some browsers would optimize the next test based on similar code from the previous test. Unlike the top answerer, I found that implicit was the worst method.
5

I find that num * 1 is simple, clear, and works for integers and floats...

Comments

4

Here is simple way to do it: var num = Number(str); in this example str is the variable that contains the string. You can tested and see how it works open: Google chrome developer tools, then go to the console and paste the following code. read the comments to understand better how the conversion is done.

// Here Im creating my variable as a string
var str = "258";


// here im printing the string variable: str
console.log ( str );


// here Im using typeof , this tells me that the variable str is the type: string
console.log ("The variable str is type: " + typeof str);


// here is where the conversion happens
// Number will take the string in the parentesis and transform it to a variable num as type: number
var num = Number(str);
console.log ("The variable num is type: " + typeof num);

Comments

3

This is probably not that fast, but has the added benefit of making sure your number is at least a certain value (e.g. 0), or at most a certain value:

Math.max(input, 0);

If you need to ensure a minimum value, usually you'd do

var number = Number(input);
if (number < 0) number = 0;

Math.max(..., 0) saves you from writing two statements.

4 Comments

Why not use Math.abs(input)? It also converts strings to positive numbers, and saves a few extra characters.
@AaronGillion: Math.max(-5, 0) will return 0; Math.abs(-5) will return 5. It depends on the use case which makes more sense.
Oh, whoops, yea, my use case was way different during whatever late night I wrote that comment.
If input can not be converted to number you will get NaN
1

7 ways to convert a String to Number:

let str = "43.2"

1. Number(str) => 43.2
2. parseInt(str) => 43
3. parseFloat(str) => 43.2
4. +str => 43
5. str * 1 => 43.2
6. Math.floor(str) => 43
7. ~~str => 43

1 Comment

Is this ordered by performance? OP asked for "fastest way".
0

You can try using UnitOf, a measurement and data type conversion library we just officially released! UnitOf is super fast, small in size, and efficient at converting any data type without ever throwing an error or null/undefined. Default values you define or UnitOf's defaults are returned when a conversion is unsuccessful.

//One liner examples
UnitOf.DataType("12.5").toFloat(); //12.5 of type Float is returned. 0 would be returned if conversion failed.
UnitOf.DataType("Not A Num").toInt(10); //10 of type Int is returned as the conversion failed.

//Or as a variable
var unit = UnitOf.DataType("12.5");
unit.toInt(5); //12.5 of type Float is returned. 5 would be returned if the conversion failed.
unit.toFloat(8); // 12 of type Int is returned. 8 would be returned if the conversion failed.

Comments

-1

The fastest way is using -0:

const num = "12.34" - 0;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.