Convert a string to a number in JavaScript

In this tutorial, we will learn how to convert a string to a number in JavaScript.

In projects, it is often needed to convert number formatted string into integer formatted number to perform specific tasks. So it is important to know how to do it.

How to convert a string to a number in JavaScript?

Variables used in code

str – string

var str = "22"

Method 1

To convert a string to a number, I used the inbuilt method parseInt() in this method.

let i = parseInt(str)

Method 2

To convert a string to a number, I used the inbuilt method Number() in this method.

let i = Number(str)

Method 3

In this method/function, I converted each character in the string to a number and multiplied it by powers of ten to get the number to its proper position, which I then added to the num variable to get the final result. For example, “22” = 2*10 + 2 = 22.

function characterToNumber(char){
    switch(char) {
        case '0':
    	    return 0
        case '1':
     	    return 1
        case '2':
     	    return 2
        case '3':
     	    return 3
        case '4':
     	    return 4
        case '5':
     	    return 5
        case '6':
     	    return 6
        case '7':
     	    return 7
        case '8':
     	    return 8
        case '9':
     	    return 9
        default:
    	    return -1
    }
}

function stringToNumber(str){
    const n = str.length
    let num = 0
    for(let i=0;i<n;i++){
        let x = characterToNumber(str[i])
        if(x !== -1){
    	    num += x*(10**(str.length-i-1))
        }
        else{
    	    return "Invalid string"
        }
    }
    return num
}
let i = stringToNumber(str)

Output

console.log(i,typeof(i))
 22, 'number'

Leave a Reply

Your email address will not be published.