最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript extracting number from string - Stack Overflow

programmeradmin4浏览0评论

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 the number values in order to calculate the price difference.

(So I wend up with ≈

var productPriceDiff = DKK 100";

or just:

var productPriceDiff = 100";)

Can anyone help me do this?

Thanks, Jakob

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 the number values in order to calculate the price difference.

(So I wend up with ≈

var productPriceDiff = DKK 100";

or just:

var productPriceDiff = 100";)

Can anyone help me do this?

Thanks, Jakob

Share Improve this question edited Jul 10, 2014 at 3:02 Jason Aller 3,65228 gold badges41 silver badges39 bronze badges asked Jun 12, 2009 at 15:41 Jakob MadsenJakob Madsen 1
  • 1 Are your numbers always going to be in a similar format? You can use a regular expression to grab just the number part then create a new Number() with the string. – Kekoa Commented Jun 12, 2009 at 15:46
Add a comment  | 

4 Answers 4

Reset to default 10

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

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.

try also:

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

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

发布评论

评论列表(0)

  1. 暂无评论