What's the fastest way to convert String to Number in 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!
What's the best way to convert a number to a string in JavaScript?
like this:
var foo = 45;
var bar = '' + foo;
Actually, even though I typically do it like this for simple convenience, over 1,000s of iterations it appears for raw speed there is an advantage for .toString()
See Performance tests here (not by me, but found when I went to write my own):
http://jsben.ch/#/ghQYR
Fastest based on the JSPerf test above: str = num.toString();
It should be noted that the difference in speed is not overly significant when you consider that it can do the conversion any way 1 Million times in 0.1 seconds.
Update: The speed seems to differ greatly by browser. In Chrome num + ''
seems to be fastest based on this test http://jsben.ch/#/ghQYR
Update 2: Again based on my test above it should be noted that Firefox 20.0.1 executes the .toString()
about 100 times slower than the '' + num
sample.
How to convert a string to an integer in JavaScript
The simplest way would be to use the native Number
function:
var x = Number("1000")
If that doesn't work for you, then there are the parseInt, unary plus, parseFloat with floor, and Math.round methods.
parseInt()
var x = parseInt("1000", 10); // You want to use radix 10
// So you get a decimal number even with a leading 0 and an old browser ([IE8, Firefox 20, Chrome 22 and older][1])
Unary plus
If your string is already in the form of an integer:
var x = +"1000";
floor()
If your string is or might be a float and you want an integer:
var x = Math.floor("1000.01"); // floor() automatically converts string to number
Or, if you're going to be using Math.floor several times:
var floor = Math.floor;
var x = floor("1000.01");
parseFloat()
If you're the type who forgets to put the radix in when you call parseInt, you can use parseFloat and round it however you like. Here I use floor.
var floor = Math.floor;
var x = floor(parseFloat("1000.01"));
round()
Interestingly, Math.round (like Math.floor) will do a string to number conversion, so if you want the number rounded (or if you have an integer in the string), this is a great way, maybe my favorite:
var round = Math.round;
var x = round("1000"); // Equivalent to round("1000", 0)
JavaScript: Performance about conversion ways from string to int
But I want to know which one is best for performance?
Test it yourself
const n = 3function first (num) { return +num}function second (num) { return num * 1}function third (num) { return ~~ num}function forth (num) { return parseInt(num)}
const count = 10000000const data = new Array(count).fill(n);
console.time('first')data.map(first)console.timeEnd('first')
console.time('second')data.map(second)console.timeEnd('second')
console.time('third')data.map(third)console.timeEnd('third')
console.time('forth')data.map(forth)console.timeEnd('forth')
Javascript to convert string to number?
There are several ways to achieve it:
Using the unary plus operator:
var n = +str;
The Number
constructor:
var n = Number(str);
The parseFloat
function:
var n = parseFloat(str);
How to convert a string to number in TypeScript?
Exactly like in JavaScript, you can use the parseInt
or parseFloat
functions, or simply use the unary +
operator:
var x = "32";
var y: number = +x;
All of the mentioned techniques will have correct typing and will correctly parse simple decimal integer strings like "123"
, but will behave differently for various other, possibly expected, cases (like "123.45"
) and corner cases (like null
).
Table taken from this answer
Related Topics
JavaScript Extract Certain Properties from All Objects in Array
How to Avoid Long Nesting of Asynchronous Functions in Node.Js
How to Programmatically Force an Onchange Event on an Input
Using the Get Parameter of a Url in JavaScript
Testing Whether a Value Is Odd or Even
How to Add Bootstrap in Angular 6 Project
JavaScript in <Head> or Just Before </Body>
How to Submit 2 Forms in One Page with a Single Submit Button
Invoke Native Date Picker from Web-App on iOS/Android
Http Status Code 401 Even Though I'm Sending Credentials in the Request
JavaScript Seconds to Minutes and Seconds
How to Pass a JavaScript Variable to Another Browser Window
JavaScript Closures and 'This'
Difference Between Window.Location.Href=Window.Location.Href and Window.Location.Reload()
Change Form Values After Submit Button Pressed
Print a Div Using JavaScript in Angularjs Single Page Application
Where Should I Declare JavaScript Files Used in My Page? in <Head></Head> or Near </Body>