snippetjavascriptCritical
How can I convert a string to an integer in JavaScript?
Viewed 0 times
howintegerconvertcanstringjavascript
Problem
How do I convert a string to an integer in JavaScript?
Solution
The simplest way would be to use the native
If that doesn't work for you, then there are the parseInt, unary plus, parseFloat with floor, and Math.round methods.
parseInt()
Unary plus
If your string is already in the form of an integer:
floor()
If your string is or might be a float and you want an integer:
Or, if you're going to be using Math.floor several times:
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.
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:
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 numberOr, 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)Code Snippets
var x = Number("1000")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])var x = +"1000";var x = Math.floor("1000.01"); // floor() automatically converts string to numbervar floor = Math.floor;
var x = floor("1000.01");Context
Stack Overflow Q#1133770, score: 3114
Revisions (0)
No revisions yet.