2016-01-20 113 views
0

我有我从一个jQuery选择html的是得到一个字符串获得数值为
例如只是需要从一个字符串

<span class="currency">$</span>"&nbsp;477,000.00" 

我只想得到477000.00值,我可以将它用作一些计算的数字。

我试了一个parseInt,它返回Nan。

这里是我的选择代码:

这里是我的实际代码:

function getSystemPrice() { 
    var currentSystemPrice = $("#bom-div-content table tbody tr td").html(); 
    currentSystemPrice = parseInt(currentSystemPrice); 
    $("#SYSTEM_PRICE_TILES_ONLY").val(currentSystemPrice); 
} 
+0

向我们显示您当前的代码。 –

+0

在输出数字之前关闭'span',这就是为什么你没有得到价值。此外,您需要删除$ anyways,否则'NaN'是解析的结果。 – SaschaM78

+0

数字的可能格式是什么。 – Tushar

回答

3

尝试:

var string = '<span class="currency">$</span>"&nbsp;477,000.00"'; 
 
var output = parseFloat(string.match(/([\d,.]+\.)/)[1].replace(/,/g, '')); 
 
document.getElementById('output').innerHTML = output;
<div id="output"></div>

UPDATE

var string = '<span class="currency">$</span>"&nbsp;477,000.00"'; 
 
var string2 = '<span class="currency">$</span>"&nbsp;12.477.000,00"'; 
 
var re = /((?:\d{1,3}[,.]?)+)[,.](\d{2})/; 
 
var m = string.match(re); 
 
var output = document.getElementById('output'); 
 
output.innerHTML += parseFloat(m[1].replace(/[,.]/g, '') + '.' + m[2]) + '\n'; 
 
m = string2.match(re); 
 
output.innerHTML += parseFloat(m[1].replace(/[,.]/g, '') + '.' + m[2]);
<pre id="output"></pre>

正则表达式的解释:

  • ( (?: non capturing group \d{1,3} 1 to 3 digits [,.]? optional comma or dot )+ at least one of those )全是包在括号所以
  • [,.]最后一个逗号(最后一个逗号或点之前数)捕捉整个事情或点(未捕获)
  • (\d{2})捕获组t帽子最后2位数匹配
+0

这将匹配'。,1,.2,.4,' – Tushar

+0

@Tushar我已经假设它在html中有有效的数字。 – jcubic

+0

这个代码是否可以工作,如果它是欧元,它会是这样的:477.000,00 –

0

你可能得到的值是多少?如果你总是得到“$” “,你可以在str.split(”;“)上分割字符串,如果你知道数字总是字符串的最后部分,你必须从结尾选择字符例如,使用str.slice(-1),当你得到字符没有意义的号码停止。

+0

该数字将始终为结局就像它一样。唯一可能改变的是,和。因为处理货币的显示方式。 –

0

试试这个。

function getSystemPrice() { 
    var currentSystemPrice = $("#bom-div-content table tbody tr td").html(); 
     currentSystemPrice = currentSystemPrice.replace("$",""); //Here you take out the $ 
     currentSystemPrice = currentSystemPrice.replace(" ",""); //Here you take out white spaces 
     currentSystemPrice = parseFloat(currentSystemPrice); //This way you will have decs if its needed 
    $("#SYSTEM_PRICE_TILES_ONLY").val(currentSystemPrice); 
    return true; 
} 
+0

你的代码可以通过使用替换工作,但是由于它不能用于代码,但我可以用“”替换字符串的某些部分,并使用此方法获取我的编号。 –

+0

你用这段代码得到了什么错误? – kpucha

0

你想解析数为int或因为有两种方法可以做到这一点

要解析为int,应该将第二个参数传递给parseInt,基数(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt)。

parseInt("10", 10); 

这是因为大多数实现使用10作为默认基数,但不是全部,所以它可能是稍后错误的微妙来源。

采取了jQuery了出来,并简单地读取数字作为一个字符串,并将其转换为浮动,我不喜欢这样的:

var tmp = "<span class='currency'>$</span>&nbsp;477,000.00".split("&nbsp;")[1]; 
parseFloat(tmp.split(",").reduce((a, b) => a + b)); 

你当然可以使用parseInt函数,而不是parseFloat的如前所述,这取决于你想要的数据的确切性质。

不知道这是您寻找的解决方案,但我想我会看看如果我可以使用减少来完成它,我不介意承认我在这里也学到了一些东西。

相关问题