Open In App

Convert a String to an Integer in JavaScript

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In JavaScript, converting a string to an integer means transforming a string that represents a numeric value into an actual integer data type. This is useful when you need to perform arithmetic operations or comparisons on numeric values stored as strings.

In this JavaScript string to integer article, You’ll learn all the methods used to convert string to integer in Javascript like parseInt JavaScript, Number method javascript, Unary operator, Math.floor method etc which are as follow.

Common methods for converting strings to integers

1. parseInt() Method in JavaScript

The parseInt() method accepts the string and radix parameter and converts it into an integer.

Syntax:

parseInt( Value, radix )

Example:

Here, we are using JavaScript parseInt() method to convert string to an integer.

javascript




let a = "100";
 
console.log("Type of a before conversion: " + typeof a);
console.log("Type of a after conversion: " + typeof parseInt(a));


Output

Type of a before conversion: string
Type of a after conversion: number

Explanation:

The code initializes a variable a with the string “100”, prints its type before and after converting it to an integer using parseInt()

2. Number() Method in JavaScript

The number() method is used to convert primitive data type to a number, if it is not convertible it returns NAN.

Syntax:

Number( value )

Example:

Here, we are using JavaScript Number() method to convert string to an integer.

Javascript




let age = "23";
let name = "Manya";
 
console.log(
    "Type of name and age before conversion: ",
    typeof age, typeof name
);
 
console.log(
    "Type of name and age after conversion: ",
    typeof Number(age), typeof Number(name)
);


Output

Type of name and age before conversion:  string string
Type of name and age after conversion:  number number

Explanation:

The code initializes variables age and name with string values representing age and a name respectively. It then displays their types before and after conversion to numbers using Number().

3. Unary Operator in JavaScript

The Unary operator(+) is used to convert a string, boolean, and non-string to a number.

Syntax:

+operand;

Example:

The unary operator to convert a string into an number.

Javascript




let age = "23";
let name = "Manya";
const number = '100';
 
console.log(
    "Type of name, age and number before conversion: ",
    typeof age, typeof name, typeof number
);
 
console.log(
    "Type of name, age and number after conversion: ",
    typeof +age, typeof +name, typeof +number
);


Output

Type of name, age and number before conversion:  string string string
Type of name, age and number after conversion:  number number number

Explanation:

The code initializes variables age, name, and number with string values representing age, a name, and a constant number respectively. It then displays their types before and after conversion to numbers using the unary plus operator +.

4. Math.floor() Method in JavaScript

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.

Javascript




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.

5. Bitwise Operator in JavaScript

Using bitwise operators like | 0 or << 0 can also perform string-to-integer conversion in a concise manner.

Syntax:

numStr | 0;   // or
numStr << 0;

Example:

The Bitwise Operator can also be used to convert a string into an number.

Javascript




let numStr = "101.45";
 
let numInt = numStr | 0;
 
console.log("Type of Number Before Conversion: "
    + typeof numStr);
     
console.log("Type of Number After Conversion: "
    + typeof parseInt(numInt));


Output

Type of Number Before Conversion: string
Type of Number After Conversion: number

Explanation:

The code initializes a variable numStr with the string “101.45”. It then uses a bitwise OR operation (|) to implicitly convert numStr to an integer, truncating its decimal part. Finally, it displays the type of numInt before and after conversion.

Error Handling in Converting Strings to Integers in JavaScript

When converting strings to integers, it’s crucial to handle potential errors to ensure your code functions correctly. Here are some common errors and how to handle them:

  • Non-numeric characters: If the string contains non-numeric characters, parseInt() and Number() might return NaN (Not a Number). You can check for this using isNaN() and gracefully handle invalid inputs.
  • Leading and trailing whitespace: Whitespace at the beginning or end of the string might be ignored by some methods. Use methods like trim() to remove whitespace before conversion.
  • Radix issues: Specifying the wrong radix in parseInt() can lead to unexpected results. Validate the radix based on the context (e.g., for hexadecimal strings, use radix 16).
  • Overflow and underflow: Converting very large or very small numbers might result in overflow or underflow. Consider using libraries like bignumber.js to handle numbers outside JavaScript’s native range.

Convert a String to an Integer in JavaScript Use Case:

1. JavaScript Program to Convert Date to Number

The JavaScript Date object is used to get dates and times. It helps in formatting the dates. We can use the new keyword to create an object for Date. To convert a Date to a Number, we use the getTime() method.

2. How to convert a string into a integer without using parseInt() function in JavaScript ?

To convert a string into an integer without using parseInt(), we can use the following:

3. How to convert string of any base to an integer in JavaScript ?

We could be using a method (or a function) provided by JavaScript called as parseInt(). 

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Last Updated : 04 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Similar Reads