How to convert a string to an integer in JavaScript
Convert a String to a Number in JavaScript is a common and simple operation. When you are working with the real project at that time you have to manage the data whereas you need to convert a string to a number or a number to a string in JavaScript. So today we will show you how to convert a string to a number in JavaScript with example.
- How to use Map, Filter, and Reduce in JavaScript
- JavaScript Arrow function
- Set a default parameter value for a JavaScript function
- Replace multiple strings in JavaScript
In Javascript, numbers can represent as actual number i.e. 28
or as string i.e."28"
. these are two different types of object so we use comparison to compare this number, it will fail.
letâs look at one example.
var num1 = 28;
var num2 = '28';
if (num1 === num2) {
console.log(true);
} else {
console.log(false);
}
To overcome this issue, we need type conversion here.
Type of methods to convert a string into a number
1. Number()
The Number() method is a function that converts the object argument to a number that represents the objectâs value. if you pass in a string with random text in it you will get NaN
. so if The Number() function canât converted to a number, NaN
is returned.
var num1 = "28";
console.log(typeof(num1)) // Output: "string"
var num2 = Number("28");
console.log(num2); // Output: 28
console.log(typeof(num2)); // Output: "number"
Here we pass string 28 to Number() function and it returns a new number value of 28
. If we checked the typeof the new number you will find that is number
.
2. parseInt()
Method parseInt() method is a function that parses a string and returns an integer with a specific radix. parseInt() function returns NaN
when the string doesnât contain number.
parseInt("28") // Output: 28
parseInt("28.51") // Output: 28
parseInt("28em") // Output: 28
parseInt("28.7xyz") // Output: 28
In the above four example, strings were converted to a 28
number. If we use Number() function for above last two examples then it returns NaN
so comparatively parseInt() function is better then Number() function.
3. parseFloat()
parseFloat() is a function, which purses a string and returns a floating point number. Also parseFloat() function returns NaN
when the string doesnât contain number.
parseFloat("28") // Output: 28
parseFloat("28.51") // Output: 28.51
parseFloat("28em") // Output: 28
parseFloat("28.7xyz") // Output: 28.7
If you want to retain the decimal part and not just get the integer part, use parseFloat() function.
Thatâs it for today.
Thank you for reading. Happy Coding..!! đ