How To Convert String To Integer In Javascript

String and integer are two important data types in JavaScript that are widely used in programming. Strings are character sequences surrounded by quotes (either single or double quotes).You can build more effective and efficient code by being aware of the various JavaScript conversion techniques for strings to integers.

A common task in JavaScript programming is converting a string to an integer. In this blog, We’ll go over the detailed steps in this blog for converting string to integer in JavaScript.

 So, let’s dive in!

Why Is There A Need to convert string to integer in javascript

Some of the reason how to convert string to integer in javascript are:-

  • Mathematical calculations: You might need to use a string to conduct mathematical operations on if it contains a numeric value. The calculations must be performed on an integer because JavaScript can only execute arithmetic operations on numeric values.
  • Data type conversion: In JavaScript, you may need to convert data from one type to another. When interacting with form data, for instance, the values will be in string format. You need to translate the string into an integer in a variable or database.
  • Sorting and comparing data: When you’re working with arrays in JavaScript, you may need to sort or compare data.
  • Input validation: You might need to confirm that the user input is a numeric value while verifying user input in a web form.
  • API requests and responses: When working with APIs, you may need to pass or receive numeric values as parameters or responses. In such cases, you need to convert string values in integers or vice versa.

Approaches to convert string to integer in JavaScript

There are five methods, how to convert string to number in javascript. Methods are listed below:-

  1. Using the function parseInt()
  2. Using the function Number()
  3. Using unary plus (+) Operator
  4. Using the Math.floor() function
  5. Using the ‘~~’ operator

Let’s have a look.

1. Using the function parseInt()

In javascript, the parsInt() function is a built-in function that accepts two arguments: the string to be converted and the number system’s base (optional).

Source Code:-

const s = “123”;

//here we are using the function on str
const num = parseInt(s);

console.log(num);

Output:-

123

Explanation of code:-

  • We had a string in the variable “s”.
  • The parseInt() function is passed the input string “10” as an argument.
  • The function parseInt() converts the string to a number value and returns it.
  • The resulting integer value, in this case 10, is saved in the variable “num.”

2. Using the function Number()

The Number() is a built-in function that is used to convert a string in an integer. The numeric representation of the input string is returned as the value.

Source Code:-

const s = ‘42’;
const integer = Number(s);
console.log(integer); 

Output:-

42

Explanation of code:-

  • The above sample code, Number() constructor takes the string value of “42” in variable ‘s’ .
  • And converts it to an integer value of 42 and stores it in variable ‘integer’ and outputs to the console.

3. Using unary plus (+) Operator

To convert a string to a number, use the Unary Plus Operator (+). The string to be converted is the only argument to this operator. The numeric representation of the input string is returned as the value.

Sample Code:-

const s = “999”;

//here we are using the function
const num = +s;

console.log(num);

Output:-

999

Explanation of code:-

  • This code converts a string to a number using built-in Number() function.
  • The Number() function is given the string “3.14” as an argument.
  • Using JavaScript’s standard numeric conversion rules, the function converts the string to the number 3.14.
  • The result is then saved in the variable “num” for later use in the programme.

4. Using the Math.floor() function:

The Math.floor() function converts a string to an integer by rounding down the string’s numeric value. This approach should be used with proper guidance because it may not work for all string values.

Sample Code:-

const s = ‘42’;

//here we are using the function
const integer = Math.floor(s);

console.log(integer); 

Output:-

42

Explanation of code:-

  • The text value 42” in the sample code above is changed to the integer 42 using the Math.floor() function.
  • The integer is stored in variable ‘integer’ and outputted to the console.

5. Using the ‘~~’ operator

Another approach to convert a string to an integer in JavaScript is to use the double tilde (~~) operator. The ‘~~’ is a bitwise operator that is used to truncate a number to an integer value. It initially coerces a string into a numeric value before truncating it to an integer value when applied to a string.

Sample Code:-

const s = ‘71’;

//here we are using the function
const integer = ~~s;

console.log(integer);

Output:-

71

Explanation of code:-

  • In the above sample code, the ‘~~’ is used to convert the string value of “42” to an integer.
  • The operator coerces the string to a numeric value, and then truncates it to an integer value using the bitwise operator.

Best approach:- Using the function parseInt()

To convert a string to an integer, use the function parseInt(). Here are the reasons for same:

  • A well-known and often used built-in function in JavaScript is parseInt(). It is straightforward to understand and maintain code that uses it because the majority of people are familiar with it.
  • The parseInt() function is versatile and can handle a wide range of input values, including strings with different radix or base values. This makes it a flexible solution because it may be applied to a range of circumstances.
  • When the input string cannot be transformed into a number, the parseInt() function returns NaN (Not a Number), making it simple for code that utilizes it to handle errors and exceptions.
  • The parseInt() function can be configured to use a specific radix or base value for the conversion, which provides greater control over the output.

Sample Problem how to convert string to Number in JavaScript

Sample Problem 1:-

Problem statement:- Nitish is building a web page that accepts user input for their age in years as a string, but he needs to convert that string to an integer value to perform calculations with it. What will be the code?

Solution:-

  • The parseInt() function is used to convert the ageStr variable, which contains “25” as a string, to an integer 25.
  • The resulting integer value is stored in the ageInt variable, which can now be used for calculations.

Solution Code:-

const ageStr = "25";

//here we are using the function
const ageInt = parseInt(ageStr);

console.log(ageInt);

Output:-

25

Sample Problem 2:-

Problem statement:- Gill is building a form in a web application that accepts user input for their phone number as a string, but he needs to convert that string to an integer to store it in a database.

Solution:-

  • Number() constructor is used to convert the phoneNoStr variable, which contains the string “555-1234”, to an integer.
  • The replace() is used to remove hyphens (-) from the string before it is converted to an integer.
  • The resulting numeric value is stored in the phoneNoInt variable, which can now be stored in a database as an integer value.

Solution Code:-

const phoneNoStr = "555-1234";

//here we are using the function
const phoneNoInt = Number(phoneNoStr.replace(/-/g, ""));

console.log(phoneNoInt); // Output: 5551234

Output:-

5551234

Sample Problem 3:-

Problem statement:- Saleem knows JavaScript, has his own restaurant, and wants to build a simple web application that calculates the total cost of a meal at a restaurant. The app takes in the cost of the meal and the tip percentage as strings, but he needs to convert them to numbers to perform the calculation. How can you help Saleem use the unary plus operator to achieve this?

Solution:-

  • The unary plus operator is used to convert the mealCostStr and tipPercent variables from strings to integers.
  • The mealCostStr variable is first multiplied by the tipPercent variable as a decimal value using the expression +mealCostStr * (+tipPercent / 100).
  • The resulting value is added to the original mealCostStr value using the expression +mealCostStr + (+mealCostStr * (+tipPercent / 100)).
  • The resulting value is then rounded to two decimal places using the toFixed() and stored in the totalCostInt variable.
  • The totalCostInt variable contains the total cost of the meal, including the tip, which can now be displayed to the user.

Solution Code:-

const mealCostStr = “25.99”;
const tipPercent = “15”;

//here we are using the function
const totalCostInt = (+mealCostStr + (+mealCostStr * (+tipPercent / 100))).toFixed(2);

console.log(totalCostInt);

Output:-

29.89

Sample Problem 4:-

Problem statement:- Priyam is developing a web application that estimates how many boxes are required to pack a certain amount of things. A maximum of 20 things can fit in each box, hence the number of boxes must be rounded up to the next full number. How does he accomplish this using Math.floor()?

Solution:-

  • The string “82” is assigned to the variable totalItems using the const keyword.
  • The Math.floor() method is used to convert the string value of totalItems to an integer value, which is then added to 19 to ensure that any remainder is rounded up to the nearest whole number when dividing by 20.
  • The result value is divided by 20 and then passed through Math.floor() again to round down to the nearest whole number.
  • The resulting value is stored in the boxesNeeded variable using the const keyword.
  • Finally, the value of the boxesNeeded variable is outputted to the console.

Solution Code:-

const totalItems = “82”;

//here we are using the function
const boxesNeeded = Math.floor((Math.floor(totalItems) + 19) / 20);

console.log(boxesNeeded);

Output:-

5

Sample Problem 5:-

Problem statement:- Vaibhaw is building a game that tracks the player’s score as a string, but he needs to convert that string to an integer to compare it with other scores.

Solution:-

  • The double tilde (~~) operator is used to convert the scoreStr variable, which contains the string “1024”, to an integer value.
  • The resulting integer value is stored in the score variable, which can now be used to compare the player’s score with other scores.

Solution Code:-

const scoreStr = "1024";

//here we are using the function
const score = ~~scoreStr;1024

console.log(score);

Output:-

1024

Conclusion

In conclusion, there are various ways to transform a string into an integer in JavaScript, each having unique benefits and applications.

The Number() constructor and the unary plus (+) operator are also popular choices, especially when dealing with other numeric data types. Finally, a specialized technique that may be used to round down a numerical value to the nearest whole number is the Math.floor() method.

Depending on the need of your code and the kind of data you’re working on, one of these methods may be more suitable than the others.