Skip to content Skip to sidebar Skip to footer

Javascript Extracting Number From String

I have a bunch of strings extracted from html using jQuery. They look like this: var productBeforePrice = 'DKK 399,95'; var productCurrentPrice = 'DKK 299,95'; I need to extract t

Solution 1:

First you need to convert the input prices from strings to numbers. Then subtract. And you'll have to convert the result back to "DKK ###,##" format. These two functions should help.

var priceAsFloat = function (price) {  
   return parseFloat(price.replace(/\./g, '').replace(/,/g,'.').replace(/[^\d\.]/g,''));
}

var formatPrice = function (price) {  
   return 'DKK ' + price.toString().replace(/\./g,',');
}

Then you can do this:

var productBeforePrice = "DKK 399,95"; 
var productCurrentPrice = "DKK 299,95";
productPriceDiff = formatPrice(priceAsFloat(productBeforePrice) - priceAsFloat(productCurrentPrice));

Solution 2:

try:

var productCurrentPrice = productBeforePrice.replace(/[^\d.,]+/,'');

edit: this will get the price including numbers, commas, and periods. it does not verify that the number format is correct or that the numbers, periods, etc are contiguous. If you can be more precise in the exact number definitions you expcet, it would help.


Solution 3:

try also:

var productCurrentPrice = productBeforePrice.match(/\d+(,\d+)?/)[0];

Solution 4:

var productCurrentPrice = parseInt(productBeforePrice.replace(/[^\d\.]+/,''));

That should make productCurrentPrice the actual number you're after (if I understand your question correctly).


Post a Comment for "Javascript Extracting Number From String"