swisstony
swisstony

Reputation: 1715

Converting a String to a Number in JS

Can someone please advise why the 'inputValue' variable in the below function is not being converted into a Number. I was expecting the second console.log to report that the variable is now a Number (since I applied parseInt to it). But apparently its still a String.

function checkIfNum(){
    var inputValue = document.getElementsByTagName('input')[0].value;
    console.log(inputValue);

    // Convert to a number
    parseInt(inputValue);

    console.log(typeof(inputValue));
}

Upvotes: 0

Views: 108

Answers (3)

Rob S.
Rob S.

Reputation: 1156

You must store the returned value from parseInt(inputValue) as a new variable or overwrite the existing one

function checkIfNum(){
var inputValue = document.getElementsByTagName('input')[0].value;
console.log(inputValue);

// Convert to a number
var newInputValue = parseInt(inputValue);

console.log(typeof(newInputValue));
}

Upvotes: 0

Amit
Amit

Reputation: 46351

Because you're not assigning the result of parseInt to anything, and specifically not to inputValue. To correct:

inputValue = parseInt(inputValue);

Upvotes: 1

CodingIntrigue
CodingIntrigue

Reputation: 78585

You haven't done anything with the result of the parseInt so as it stands, you are doing typeof on the original value of inputValue which is a string. Assign the result of parseInt to inputValue and your code will work fine:

function checkIfNum(){
    var inputValue = document.getElementsByTagName('input')[0].value;
    console.log(inputValue);

    // Assign the result of parseInt
    inputValue = parseInt(inputValue, 10);

    console.log(typeof(inputValue));
}

JsFiddle (Stack Snippets appears to be down).

It's also worth nothing that I added a radix to your parseInt call to ensure it's parsed as decimal on some older browsers.

Upvotes: 3

Related Questions