Javascript从字符串中提取数字 [英] Javascript extracting number from string

查看:129
本文介绍了Javascript从字符串中提取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a bunch of strings extracted from html using jQuery.

它们看起来像这样:

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

我需要提取数字值才能计算出价格差异.

I need to extract the number values in order to calculate the price difference.

(所以我想出了≈

var productPriceDiff = DKK 100";

或者只是:

var productPriceDiff = 100";)

有人可以帮我吗?

谢谢, 雅各布

推荐答案

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

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

这篇关于Javascript从字符串中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆