Code Premix

How to convert a string to an integer in JavaScript

📅June 18, 2021
🗁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.

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()
  2. parseInt()
  3. parseFloat()

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..!! 🙂