Skip to content
Advertisement

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

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

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

Advertisement

Answer

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!

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement