Search code examples
javascriptjquerysumcalculated-columns

jQuery sum table toFixed not working properly


I have dynamic table with data that can be formatted differently. For example: 500 500,57 1500,00 1.500,00. Currently I'm doing str_replace to remove first dot on thousandth and then replace comma with dot.

echo str_replace(array(".", ",",), array("", "."), $row['rad_iznos']); 

That works fine and I get only thousandth with dot separator on decimal numbers. However when I use toFixed(2) option on sum the value of decimal is left behind and it should work according to this: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tofixed . As you can see only decimals after 2 digits are rounded up.

var totals=[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]+=parseInt( $(this).html());
                });
            });
            $("#sum_table td.totalCol").each(function(i){  
                $(this).html('<span style="font-weight: bold;">'+totals[i].toFixed(2)+' kn</span>');
            });

        });

You can see example here: enter image description here .57 is missing and I just don't understand logic behind it. Please advise. thousandths value is correct.


Solution

  • The issue is not with .toFixed() but with:

    totals[i] += parseInt($(this).html());
    

    which will add each row's value as an integer - thus losing the decimal places as it goes, so when it gets to .toFixed() it's already lost the decimal places.

    The solution is to use parseFloat() instead, to keep the decimal places:

    totals[i] += parseFloat($(this).html());