Skip to content
Advertisement

Remove currency symbol from string and convert to a number using a single line in Javascript

I have a string below that is a price in £, I want to remove the currency symbol and then convert this into a number/price I can use to compare against another value (eg. X >= Y …)

£14.50

I have previously converted strings to numbers used for currency with

var priceNum = parseFloat(price);

IDEAL OUTCOME

14.50 as a number value. Can this be done in a single line?

Advertisement

Answer

If the currency symbol will always be there, just use substring:

var priceNum = parseFloat(price.substring(1));

If it may or may not be there, you could use replace to remove it:

var priceNum = parseFloat(price.replace(/£/g, ""));

Beware that parseFloat("") is 0. If you don’t want 0 for an empty input string, you’ll need to handle that. This answer has a rundown of the various way to convert strings to numbers in JavaScript and what they do in various situations.

Side note: Using JavaScript’s standard numbers for currency information is generally not best practice, because if things like the classic 0.1 + 0.2 issue (the result is 0.30000000000000004, not 0.3). There are various libraries to help, and BigInt is coming to JavaScript as well (it’s a Stage 3 proposal at the moment, currently shipping in Chrome). BigInt is useful because you can use multiples of your basic currency (for instance, * 100 for pounds and pence).

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement