How do I convert a string to an integer in JavaScript?
How do I 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";
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");
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"));
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)
Try parseInt function:
var number = parseInt("10");
But there is a problem. If you try to convert "010" using parseInt function, it detects as octal number, and will return number 8. So, you need to specify a radix (from 2 to 36). In this case base 10.
parseInt(string, radix)
Example:
var result = parseInt("010", 10) == 10; // Returns true
var result = parseInt("010") == 10; // Returns false
Note that parseInt ignores bad data after parsing anything valid.
This guid will parse as 51:
var result = parseInt('51e3daf6-b521-446a-9f5b-a1bb4d8bac36', 10) == 51; // Returns true
ParseInt() and + are different
parseInt("10.3456") // returns 10
+"10.3456" // returns 10.3456
In Javascript, you can do the following:-
ParseInt
parseInt("10.5") //returns 10
Multiplying with 1
var s = "10";
s = s*1; //returns 10
Using Unary Operator (+)
var s = "10";
s = +s; //returns 10
Using Bitwise Operator
(Note: It starts to break after 2140000000. Ex:- ~~"2150000000" = -2144967296)
var s= "10.5";
s = ~~s; //returns 10
Using Math.floor() or Math.ceil()
var s = "10";
s = Math.floor(s) || Math.ceil(s); //returns 10
Also as a side note: Mootools has the function toInt() which is used on any native string (or float (or integer)).
"2".toInt() // 2
"2px".toInt() // 2
2.toInt() // 2
Here is the easiest solution
let myNumber = "123" | 0;
More easy solution
let myNumber = +"123";
The easiest way would be to use + like this
const strTen = "10"
const numTen = +strTen // string to number conversion
console.log(typeof strTen) // string
console.log(typeof numTen) // number
function parseIntSmarter(str) {
// ParseInt is bad because it returns 22 for "22thisendsintext"
// Number() is returns NaN if it ends in non-numbers, but it returns 0 for empty or whitespace strings.
return isNaN(Number(str)) ? NaN : parseInt(str, 10);
}
+numStr is easy to use and better performant compare with othersconsole.log(+'123.45') //=> 123.45
parseInt(numStr) for integersparseFloat(numStr) for both integers and decimalsconsole.log(parseInt('123.456')) //=> 123
console.log(parseFloat('123')) //=> 123
round(numStr),floor(numStr),ceil(numStr) for integersNumber(numStr) for both integers and decimalsconsole.log(Math.floor('123')) //=> 123
console.log(Math.round('123.456')) //=> 123
console.log(Math.ceil('123.454')) //=> 124
console.log(Number('123.123')) //=> 123.123
+numStr,numStr-0,1*numStr,numStr*1,numStr/1numStr+0 , it returns stringconsole.log(+'123') //=> 123
console.log('002'-0)//=> 2
console.log(1*'5') //=> 5
console.log('7.7'*1) //=> 7.7
console.log(3.3/1) //=>3.3
console.log('123.123'+0, typeof ('123.123'+0)) //=> 123.1230 string
~~numStr or left shift 0 numStr<<0console.log(~~'123') //=> 123
console.log('0123'<<0) //=> 123
console.log(~~'123.123') //=> 123
console.log('123.123'<<0) //=> 123
// parsing
console.log(parseInt('123.456')) //=> 123
console.log(parseFloat('123')) //=> 123
// function
console.log(Math.floor('123')) //=> 123
console.log(Math.round('123.456')) //=> 123
console.log(Math.ceil('123.454')) //=> 124
console.log(Number('123.123')) //=> 123.123
// unary
console.log(+'123') //=> 123
console.log('002'-0)//=> 2
console.log(1*'5') //=> 5
console.log('7.7'*1) //=> 7.7
console.log(3.3/1) //=>3.3
console.log('123.123'+0, typeof ('123.123'+0)) //=> 123.1230 string
//bitwise
console.log(~~'123') //=> 123
console.log('0123'<<0) //=> 123
console.log(~~'123.123') //=> 123
console.log('123.123'<<0) //=> 123
You can use plus. For example:
var personAge = '24';
var personAge1 = (+personAge)
then you can see the new variable's type bytypeof personAge1 ; which is number.
Another option is to double XOR the value with itself:
var i = 12.34;
console.log('i = ' + i);
console.log('i ⊕ i ⊕ i = ' + (i ^ i ^ i));
This will output:
i = 12.34
i ⊕ i ⊕ i = 12
I only added one plus(+) before string and that was solution!
+"052254" //52254
Hope it helps ;)
Summing the multiplication of digits with their respective power of ten:
i.e: 123 = 100+20+3 = 1*100 + 2+10 + 3*1 = 1*(10^2) + 2*(10^1) + 3*(10^0)
function atoi(array) {
// use exp as (length - i), other option would be to reverse the array.
// multiply a[i] * 10^(exp) and sum
let sum = 0;
for (let i = 0; i < array.length; i++) {
let exp = array.length-(i+1);
let value = array[i] * Math.pow(10,exp);
sum+=value;
}
return sum;
}
The safest way to ensure you get a valid integer:
let integer = (parseInt(value, 10) || 0);
Examples:
// Example 1 - Invalid value:
let value = null;
let integer = (parseInt(value, 10) || 0);
// => integer = 0
// Example 2 - Valid value:
let value = "1230.42";
let integer = (parseInt(value, 10) || 0);
// => integer = 1230
// Example 3 - Invalid value:
let value = () => { return 412 };
let integer = (parseInt(value, 10) || 0);
// => integer = 0
I use this
String.prototype.toInt = function (returnval) {
var i = parseInt(this);
return isNaN(i) ? returnval !== undefined ? returnval : - 1 : i;
}
this way I always get an int back.
// return 200.12// return 200.12// return 200// return 200// return 200// return 200// return NaNIt will return the first number
// return 200// return 200// return NaN// return 200.10---
round a number to the nearest integer
// return 200// return 200// return 200This (probably) isn't the best solution for parsing an integer, but if you need to "extract" one, for example:
"1a2b3c" === 123
"198some text2hello world!30" === 198230
// ...
this would work (only for integers):
var str = '3a9b0c3d2e9f8g'
function extractInteger(str) {
var result = 0;
var factor = 1
for (var i = str.length; i > 0; i--) {
if (!isNaN(str[i - 1])) {
result += parseInt(str[i - 1]) * factor
factor *= 10
}
}
return result
}
console.log(extractInteger(str))
Of course, this would also work for parsing an integer, but would be slower than other methods.
You could also parse integers with this method and return NaN if the string isn't a number, but I don't see why you'd want to since this relies on parseInt internally and parseInt is probably faster.
var str = '3a9b0c3d2e9f8g'
function extractInteger(str) {
var result = 0;
var factor = 1
for (var i = str.length; i > 0; i--) {
if (isNaN(str[i - 1])) return NaN
result += parseInt(str[i - 1]) * factor
factor *= 10
}
return result
}
console.log(extractInteger(str))