What's the fastest way to convert String to Number in JavaScript?

Javascript

Javascript Problem Overview


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

'a' => NaN
'1' => 1
1 => 1

Javascript Solutions


Solution 1 - Javascript

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!

Solution 2 - Javascript

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 :)

Solution 3 - Javascript

Prefix the string with the + operator.

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

Solution 4 - Javascript

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.

Solution 5 - Javascript

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);

Solution 6 - Javascript

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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.

Solution 9 - Javascript

The fastest way is using -0:

const num = "12.34" - 0;

Solution 10 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbeatakView Question on Stackoverflow
Solution 1 - JavascriptbeatakView Answer on Stackoverflow
Solution 2 - JavascriptGone CodingView Answer on Stackoverflow
Solution 3 - JavascriptPratheepView Answer on Stackoverflow
Solution 4 - Javascriptuser3784814View Answer on Stackoverflow
Solution 5 - JavascriptEdmundoView Answer on Stackoverflow
Solution 6 - JavascriptDaniel SmithView Answer on Stackoverflow
Solution 7 - JavascriptDan DascalescuView Answer on Stackoverflow
Solution 8 - JavascriptDigidemicView Answer on Stackoverflow
Solution 9 - JavascriptArturasView Answer on Stackoverflow
Solution 10 - JavascriptRamin eghbalianView Answer on Stackoverflow