admin管理员组文章数量:1312985
I am trying to get sum of rows of my table:
td1 val = $5,000.00; td2 val = $3000.00;
And I am using the following code:
var totalnum = 0;
$('.num').each(function(){
totalnum+= parseFloat($(this).html());
});
$('.total_num').html(totalnum);
This code works perfect if I remove money formatting from the number, otherwise it gives NaN
as a result even if I am using parseFloat
.
What am I missing?
I am trying to get sum of rows of my table:
td1 val = $5,000.00; td2 val = $3000.00;
And I am using the following code:
var totalnum = 0;
$('.num').each(function(){
totalnum+= parseFloat($(this).html());
});
$('.total_num').html(totalnum);
This code works perfect if I remove money formatting from the number, otherwise it gives NaN
as a result even if I am using parseFloat
.
What am I missing?
Share Improve this question edited Sep 16, 2011 at 8:20 Ben Everard 13.8k14 gold badges68 silver badges96 bronze badges asked Sep 16, 2011 at 8:00 seoppcseoppc 2,8247 gold badges46 silver badges79 bronze badges 1- 1 what does .num elements contain? Could you please post an html snippet? – mamoo Commented Sep 16, 2011 at 8:03
3 Answers
Reset to default 4Try:
var totalnum = 0;
$('.num').each(function(){
totalnum+= parseFloat($(this).html().substring(1).replace(',',''));
});
$('.total_num').html('$' + totalnum);
This will remove the $ (or whatever currency symbol) from the beginning and all mas before doing the parseFloat and put it back for the total.
Alternatively you could use the jQuery FormatCurrency plugin and do this:
totalnum+= $(this).asNumber();
If you add $
to the value, it is no longer an integer, and can no longer be calculated with.
Trying to make the formatted value back into a number is a bad idea. You would have to cater for different currency symbols, different formattings (e.g. 1.000,00
) and so on.
The very best way would be to store the original numeric value in a separate attribute. If using HTML 5, you could use jQuery's data()
for it:
<td class="num" data-value="1.25">$1.25</td>
....
var totalnum = 0;
$('.num').each(function(){
totalnum+= parseFloat($(this).data("value"));
});
$('.total_num').html(totalnum);
this way, you separate the formatted result from the numeric value, which saves a lot of trouble.
Try removing $
and any other character not part of the float type:
var totalnum = 0;
$('.num').each(function(){
var num = ($(this).html()).replace(/[^0-9\.]+/g, "");
totalnum+= parseFloat(num);
});
$('.total_num').html(totalnum);
Edit: updated replace
to remove all non-numerical characters (except periods) as per this answer.
本文标签: jqueryjavascript parse float errorStack Overflow
版权声明:本文标题:jquery - javascript parse float error - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741891296a2403319.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论