pertrai1
pertrai1

Reputation: 4318

How to convert a currency to number

Based off a simlar question asked here - How to convert a currency string to a double with jQuery or Javascript?, I need to take a currency that can be in the format of

-143,000.00 and convert it for 2 scenarios:

  1. Where the output would be -143000.00
  2. Where the output would be -1430000

I am not good at all with regular expressions so I have tried some hack such as these 2 below:

  1. I need to remove all of the currency except for the -
const value = "-143,000.00";
Number(value.replace(/[^0-9.,]+/g, ''))

and my second use case is I need to remove all but keep the - and the .

const value = "-143,000.00";
Number(value.replace(/[^0-9.-]+/g, ''));

Thank you for assistance that you can give.

Upvotes: 0

Views: 330

Answers (1)

Mohsen Alyafei
Mohsen Alyafei

Reputation: 5547

Is this what you are looking for?

const value = "-143,000.00";

var n1 = value.replace(/([^\d.+-]+)/g,"");
var n2 = Number(n1);

console.log("n1 : ",n1)   // "-143000.00"
console.log("n2 : ",n2)   // -143000

Upvotes: 1

Related Questions