Make parseFloat convert variables with commas into numbers

Travis picture Travis · Nov 30, 2014 · Viewed 10.6k times · Source

I'm trying to get parseFloat to convert a userInput (prompt) into a number.

For example:

var userInput = prompt("A number","5,000") 
function parse_float(number) {
    return parseFloat(number)
}

When userInput = 5,000, parse_Float(userInput) returns 5.

However, if the user was inputting a value to change something else (ie: make a bank deposit or withdrawl) Then I to work properly, parse.Float(userInput) needs to return 5000, not 5. If anyone could tell me how to do this it would help me so much. Thanks in advance.

Answer

Lambda Fairy picture Lambda Fairy · Nov 30, 2014

Your answer is close, but not quite right.

replace doesn't change the original string; it creates a new one. So you need to create a variable to hold the new string, and call parseFloat on that.

Here's the fixed code:

function parseFloatIgnoreCommas(number) {
    var numberNoCommas = number.replace(/,/g, '');
    return parseFloat(numberNoCommas);
}

I also renamed the function to parseFloatIgnoreCommas, which better describes what it does.