How to use regex for currency

I need to get a price from one item and add it to another.

I use this:

\$\d+(?:\.\d+)? 

It seems to work for $0.50 , $1.00 , $20.00 , $200.00 , but I hit a brick wall at $1,000.00 and $ 10,000.00

( $10,000.00 unlikely to ever be used).

The wrist is turning me off.

** Change **

I took an hour to get back to the heaps of answers. Before I go through them, I thought that I would clarify and not answer all the comments:

The platform used automatically generates the total number of items in the shopping cart. It receives the visualization in the element - this changes depending on whether the user adds or removes.

The value is unlikely to go to 10,000.00, because the cost of the product is not so high.

I am new to using regex and it took me a while to get this far, so the question is.

Auto-generated HTML:

 <span vertical="False" quote="False" id="catCartSummary"> <table cellspacing="0" class="cartSummaryTable"> <tbody> <tr> <td class="cartSummaryItem">3 item(s), Total: $115.00 <a href="#" class="cartSummaryLink">View Cart</a></td> </tr> </tbody> </table> </span> 

I just need the $ value in this case $ 115.00 - But I need it to work for $ 1,000.00

+6
source share
6 answers

Replace the non-digit and non-dot characters with '' , then apply parseFloat :

 var currencyValue = parseFloat("$1,000.50".replace(/[^\d\.]/g,'')); console.log( currencyValue ) ; //1000.5 

UPDATE: If your HTML Auto generator generates the correct currency strings, then

 /\$\S+/g 

regexp is enough to extract all currencies:

 var currencies = $('#cartSummaryItem').text().match(/\$\S+/g); // ["$115.00"] 

Then you can convert them to numbers to do math exercises on them:

 var currenciesAsNumbers = currencies.map( function(item){ return parseFloat( item.replace(/[^\d\.]/g,'') ); }); // [115] 
+10
source

This works for me:

 /\$\d+(,\d+)*(?:\.\d+)?/g 

Demo

I found a great regex that grabs every valid currency and picks it up a bit for your needs:

 /^\$[0-9]{1,3}(?:[0-9]*(?:[.,][0-9]{2})?|(?:,[0-9]{3})*(?:\.[0-9]{2})?|(?:\.[0-9]{3})*(?:,[0-9]{2})?)$/g 

Demo

Regular Expression Source

+2
source

Change something like this:

 \$(?:\d{1,3},)*\d+(?:\.\d+)? 

or

  \$\d{1,3}(,\d{3})*(?:\.\d+)? 
+1
source
 var re = /^\d{1,3}(\,\d{3})*(?:\.\d+)?$/; console.log(re.test('0.50')); console.log(re.test('1')); console.log(re.test('20.50')); console.log(re.test('200.50')); console.log(re.test('2,000')); console.log(re.test('2,000.50')); console.log(re.test('20,000')); console.log(re.test('20,000.00')); console.log(re.test('1,000,000')); console.log(re.test('1,000,000.50')); 
+1
source

Disabling the currency symbol as well as the comma can be easily achieved using this RegEx with the replacement: [^ .0-9]

Demo is available here: http://rubular.com/r/Gwkx62RtLa

+1
source

I got it:

 ^\d{1,3}(,\d{3})*(\.\d+)?$ 

Only the number will match, not including the currency symbol.

0
source

Source: https://habr.com/ru/post/916070/


All Articles