Searching how to convert string to integer in JavaScript? Here is 6 ways how to do it
Making a conversion of integer to JavaScript is a common task for every frontend developer, and therefore there is many solutions for this small problem.
1. Convert string to integer by using Number
var strToNum = Number("65");
console.log(strToNum);
// output => 65
2. Convert string to integer by using parseInt
var strToNum = parseInt("65");
console.log(strToNum);
// output => 65
3. Convert string to integer by using Math.floor
var strToNum = Math.floor("65");
console.log(strToNum);
// output => 65
4. Convert string to decimal number by using parseFloat
var strToNum = parseFloat("65.12");
console.log(strToNum);
// output => 65.12
5. Convert string to decimal rounded number
var strToNum = parseFloat("65.12").toFixed(0)
console.log(strToNum);
// output => 65
// OR
var strToNum = Math.floor(Number("65.12"))
console.log(strToNum);
// output => 65
6. Convert string to number by multiplying it by one
This method seems to be the fastest way to convert string to integer:
var strToNum = "65"*1
console.log(strToNum);
// output => 65
and it also works for decimal values:
var strToNum = "65.12"*1
console.log(strToNum);
// output => 65.12