7

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?

Gracie
  • 896
  • 5
  • 14
  • 34

3 Answers3

17

I found this very helpful

var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9\.-]+/g,""));

Convert (Currency) String to Float

Karim Samir
  • 1,470
  • 17
  • 17
  • This works like magic! It safely parses any formatting like `'+1.997 €'`. Heck even something erroneous like `'stack -1.5 overflow'`. – Alex Pappas May 04 '21 at 03:22
13

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).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • This is great, thanks. How could I add a $ option as well? To detect both £ and $? – Gracie Feb 10 '19 at 15:00
  • @Gracie - The first one already does because it blindly skips the first character. For the second one, you'd use the regular expression `/[£$]/g` instead. – T.J. Crowder Feb 10 '19 at 15:02
0

try this number-formatter-npm library. This library is fantastic.

npm i number-formatter-npm

documentation:https://www.npmjs.com/package/number-formatter-npm

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 04 '21 at 08:53