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)
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.
JavaScript string and number conversion
You want to become familiar with parseInt()
and toString()
.
And useful in your toolkit will be to look at a variable to find out what type it is—typeof
:
<script type="text/javascript">
/**
* print out the value and the type of the variable passed in
*/
function printWithType(val) {
document.write('<pre>');
document.write(val);
document.write(' ');
document.writeln(typeof val);
document.write('</pre>');
}
var a = "1", b = "2", c = "3", result;
// Step (1) Concatenate "1", "2", "3" into "123"
// - concatenation operator is just "+", as long
// as all the items are strings, this works
result = a + b + c;
printWithType(result); //123 string
// - If they were not strings you could do
result = a.toString() + b.toString() + c.toString();
printWithType(result); // 123 string
// Step (2) Convert "123" into 123
result = parseInt(result,10);
printWithType(result); // 123 number
// Step (3) Add 123 + 100 = 223
result = result + 100;
printWithType(result); // 223 number
// Step (4) Convert 223 into "223"
result = result.toString(); //
printWithType(result); // 223 string
// If you concatenate a number with a
// blank string, you get a string
result = result + "";
printWithType(result); //223 string
</script>
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
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!
Related Topics
Why and When to Use Default Export Over Named Exports in Es6 Modules
How to Stop Events Bubbling in Jquery
How to Send Data in Request Body with a Get When Using Jquery $.Ajax()
How to Sum the Values of a JavaScript Object
Using Raw Image Data from Ajax Request for Data Uri
How to Read the Correct Time/Duration Values from Google Spreadsheet
Promises for Promises That Are Yet to Be Created Without Using the Deferred [Anti]Pattern
Onclick Event Binding in React.Js
How to Access Nested JSON Data
JSON Transfer of Bigint: 12000000000002539 Is Converted to 12000000000002540
Event.Wheeldelta Returns Undefined
Get Selected HTML in Browser via JavaScript
Create Copy of Multi-Dimensional Array, Not Reference - JavaScript
Why Can't I Assign a New Value to "This" in a Prototype Function