131

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

'a' => NaN
'1' => 1
1 => 1
beatak
  • 9,185
  • 10
  • 33
  • 42
  • What is fastest is dependant on the optimizations in a given implementation at a given time. There's no objectively "fastest" way. – I Hate Lazy Oct 12 '12 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? – raina77ow Oct 12 '12 at 15:50
  • A previous jsperf test: http://jsperf.com/converting-string-to-int/3 – epascarello Oct 12 '12 at 15:50
  • here a good performance comparison of the different methods: http://jsben.ch/#/NnBKM – EscapeNetscape Oct 25 '16 at 08:12
  • **See Also**: [How to convert a string to an integer in JavaScript?](https://stackoverflow.com/q/1133770/1366033) – KyleMit Oct 12 '21 at 19:41

10 Answers10

206

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!

EscapeNetscape
  • 2,892
  • 1
  • 33
  • 32
beatak
  • 9,185
  • 10
  • 33
  • 42
  • 7
    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? – Matthew Wilcoxson Nov 04 '13 at 16:26
  • 1
    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`. – Tomas Nov 06 '13 at 14:22
  • 6
    @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. – Nolo Sep 27 '14 at 14:26
  • 2
    Chrome 61.0.3163. Number() is fastest of all. – Dmitry Petukhov Oct 12 '17 at 04:40
  • I just compared `Number()` to `~~` (just a few runs on https://jsben.ch), and `Number()` won, though sometimes it was nearly even. – Andrew Jan 21 '21 at 23:48
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 :)
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • 5
    Be really careful for numbers larger than 2147483647. eg: `~~4294967296` returns `0`. – Joseph Goh Nov 27 '17 at 03:57
  • @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 – iCollect.it Ltd Nov 27 '17 at 09:10
  • @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 – iCollect.it Ltd Nov 27 '17 at 09:14
10

Prefix the string with the + operator.

console.log(+'a') // NaN
console.log(+'1') // 1
console.log(+1) // 1
Pratheep
  • 936
  • 1
  • 7
  • 17
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.

user3784814
  • 89
  • 1
  • 1
  • 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. – Jean Jul 16 '14 at 08:23
  • Here's a [jsperf of various bitwise operators](http://jsperf.com/best-of-string-to-number-conversion-allowing-defaultnan) 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. – Pluto Sep 23 '14 at 23:37
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);
Edmundo
  • 49
  • 5
4

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

Daniel Smith
  • 535
  • 1
  • 5
  • 10
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.

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
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

Ramin eghbalian
  • 2,348
  • 1
  • 16
  • 36
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.
Digidemic
  • 71
  • 4
-1

The fastest way is using -0:

const num = "12.34" - 0;
Arturas
  • 192
  • 1
  • 5