Ingus Graholskis Ingus Graholskis - 1 month ago 6
HTML Question

how to calculate values from table where there is space in number and comma

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

Answer

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"

Comments