Convert String to an Integer using Math.floor() Method
The Math.floor() method is used to convert a string into number.
Syntax:
Math.floor( numStr )
Example:
The Math.floor() method is used to convert a string into an number.
let numStr = "101.45";
let numInt = Math.floor(parseFloat(numStr));
console.log("Type of Number Before Conversion: " + typeof numStr);
console.log("Type of Number After Conversion: " + typeof numInt);
Output
Type of Number Before Conversion: string Type of Number After Conversion: number
Explanation
Here, parseFloat()
is used to convert the string numStr
to a floating-point number before applying Math.floor()
. This ensures that the result is a number.
Convert a String to an Integer in JavaScript
In JavaScript, it’s quite common to find yourself with a number trapped inside a string. This can happen when you’re dealing with user input, reading data from a file, or working with a third-party API. But JavaScript provides several handy methods to free that number and convert it into an integer. This is super useful when you need to do some math or comparisons with those numbers.
Table of Content
- Approach 1: Convert String to an Integer using parseInt() Method
- Approach 2: Convert String to an Integer using Number() Method
- Approach 3: Convert String to an Integer using Unary Operator
- Approach 4: Convert String to an Integer using Math.floor() Method
- Approach 5: Convert String to an Integer using Bitwise Operator
- Error Handling in Converting Strings to Integers in JavaScript