Thursday, December 26, 2024
Google search engine
HomeLanguagesJavascriptConvert a string to an integer in JavaScript

Convert a string to an integer in JavaScript

In this article, we will convert a string into an integer in Javascript. In JavaScript parseInt() function (or a method) is used to convert the passed-in string parameter or value to an integer value itself. This function returns an integer of the base which is specified in the second argument of the parseInt() function. JavaScript parseInt() function returns Nan( not a number) when the string doesn’t contain a number. We can convert a string to javascript by the following methods:

Using the parseInt() method: JavaScript parseInt() Method is used to accept the string and radix parameter and convert it into an integer.

Syntax:

parseInt(Value, radix)

Example 1: In this example, we will convert a string value to an integer using the parseInt() function with no second parameter.JavaScript ParseInt() function converts the number which is present in any base to base 10. It parses a string and converts it until it faces a string literal and stops parsing. 

javascript




function convertStoI() {
    let a = "100";
    let b = parseInt(a);
    console.log("Integer value is" + b);
    let d = parseInt("3 11 43");
    console.log('Integer value is ' + d);
}
convertStoI();


Output:

Integer value is 100
Integer value is 3

Example 2: In this example, we will convert a string value to an integer using the parseInt() function with a second parameter.

javascript




function convertStoI() {
    let r = parseInt("1011", 2);
    let k = parseInt("234", 8);
    console.log('Integer value is ' + r);
    console.log("integer value is " + k);
    console.log(parseInt("528neveropen"));
}
convertStoI();


Output:

Integer value is 11
integer value is 156
528

Using the Number() method: In Javascript, the Number() method is used to convert any primitive data type to a number, if it is not convertible it returns NAN.

Syntax:

Number(value)

Example: In this example, we will see the use of the Number() method.

Javascript




let age = "23";
let name = "Manya";
console.log(Number(age));
console.log(Number(name)) ;


Output:

23
NaN

Using the Unary Operator: In Javascript, the Unary operator(+) is used to convert a string, boolean, and non-string to a number.

Syntax:

+op;

Example: In this example, we will see the use of the unary operator.

Javascript




let age = "23";
let name = "Manya";
const number = '100';
console.log(+age);
console.log(+name);
console.log(+number);


Output:

23
NaN
100

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.

RELATED ARTICLES

Most Popular

Recent Comments