4

我有一堆使用 jQuery 从 html 中提取的字符串。

它们看起来像这样:

var productBeforePrice = "DKK 399,95";
var productCurrentPrice = "DKK 299,95";

我需要提取数值以计算价格差异。

(所以我找到了≈

var productPriceDiff = DKK 100";

要不就:

var productPriceDiff = 100";)

谁能帮我做到这一点?

谢谢,雅各布

4

4 回答 4

10

首先,您需要将输入价格从字符串转换为数字。然后减去。您必须将结果转换回“DKK ###,##”格式。这两个功能应该有所帮助。

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

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

然后你可以这样做:

var productBeforePrice = "DKK 399,95"; 
var productCurrentPrice = "DKK 299,95";
productPriceDiff = formatPrice(priceAsFloat(productBeforePrice) - priceAsFloat(productCurrentPrice));
于 2009-06-12T16:04:40.960 回答
5

尝试:

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

编辑:这将获得包括数字、逗号和句点在内的价格。它不验证数字格式是否正确或数字、句点等是否连续。如果您可以在您期望的确切数字定义中更加精确,那将有所帮助。

于 2009-06-12T15:47:22.907 回答
2

也试试:

var productCurrentPrice = productBeforePrice.match(/\d+(,\d+)?/)[0];
于 2009-06-12T15:51:48.137 回答
1
var productCurrentPrice = parseInt(productBeforePrice.replace(/[^\d\.]+/,''));

这应该使 productCurrentPrice 成为您所追求的实际数字(如果我正确理解您的问题)。

于 2009-06-12T15:58:08.950 回答