Search code examples
javascriptstring-conversion

JavaScript: How do I convert input that contains commas from a user to a number?


When I'm inputting test values, numbers to be specific, into my pay calculation script, it works fine (Ex. 10000). But when I input a test value with a comma (think "10,000" or "$10,000"), the script reads the values up to where the comma would (think "10" instead of "10,000". How would I resolve this issue.


Solution

  • var valueFromPrompt = window.prompt(...)
    var valueNowANumber = +valueFromPrompt.replace(/[^\d\.]/g, '');
    

    Replace all non-numeric (pattern /[^\d\.]/g) with blank. The leading + converts the string to a number. Converting a blank string (because there's no number in the raw string) makes it 0.

    Now this won't cover all edge cases for numbers, so you might want to tweak the pattern. You might want to read more about Regular Expressions