Reputation: 1044
I have code that calculate value in HTML table. It works if I use .(dot) but not when I use ,(comma)
also my numbers have space if number bigger than 1000 example 2 476,98
how can I make it working as I need?
Javascript:
var totals = [0, 0, 0, 0, 0, 0];
$(document).ready(function () {
var $dataRows = $("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function () {
$(this).find('.rowDataSd').each(function (i) {
totals[i] += parseFloat($(this).html());
});
});
$("#sum_table td.totalCol").each(function (i) {
$(this).html("kopā: " + totals[i].toFixed(2));
});
});
And here its on jsfiddle
Upvotes: 0
Views: 84
Reputation: 4160
You need to detect ,
and replace them by .
and space by nothing
""
.
On this line
totals[i] += parseFloat($(this).html());
replace it by this:
totals[i] += parseFloat($(this).text().replace(",",".").replace(/ /g, ""));
the / /g
is a regular expression to detect multiple spaces on a string. example "1 932 123" will convert to "1932123"
Upvotes: 2
Reputation: 28529
var totals=[0,0,0,0];
$(document).ready(function(){
var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.rowDataSd').each(function(i){
totals[i]+=parseFloat( $(this).html().replace(/[^0-9.]/g, ''));
});
});
$("#sum_table td.totalCol").each(function(i){
$(this).html("kopā: "+totals[i].toFixed(2));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="sum_table" border="1">
<tr class="titlerow">
<td align="center">plan1
</tr>
<tr class="titlerow">
<td align="center">EUR
</tr>
<tbody>
<tr>
<td class="rowDataSd" align="right" nowrap>2 358,94
</tr>
<tr>
<td class="rowDataSd" align="right" nowrap>3
</tr>
<tr>
<td class="totalCol"></td>
</tr>
</tbody></table>
Upvotes: 1
Reputation: 2211
<script>
var totals = [0, 0, 0, 0, 0, 0];
$(document).ready(function () {
var $dataRows = $("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function () {
$(this).find('.rowDataSd').each(function (i) {
totals[i] += parseFloat($(this).text().replace(/[^\d.-]/g, ''));
});
});
$("#sum_table td.totalCol").each(function (i) {
$(this).text("kopā: " + totals[i].toFixed(2));
});
});
</script>
Upvotes: 3