首页 > 解决方案 > jQuery sum table toFixed 无法正常工作

问题描述

我有动态表,其中的数据可以采用不同的格式。例如:500 500,57 1500,00 1.500,00。目前我正在执行 str_replace 以删除千分之一的第一个点,然后用点替换逗号。

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

这很好用,我在十进制数字上只得到千分之一的点分隔符。但是,当我在 sum 上使用 toFixed(2) 选项时,十进制的值被留下,它应该按照以下方式工作:https ://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tofixed 。如您所见,只有 2 位数字四舍五入后的小数。

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>');
            });

        });

您可以在此处查看示例:在此处输入图像描述 .57 丢失,我只是不了解其背后的逻辑。请指教。千分之一的值是正确的。

标签: javascriptjquerysumcalculated-columns

解决方案


问题不在于,.toFixed()而是在于:

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

这会将每一行的值添加为整数 - 因此会丢失小数位,所以当它到达时.toFixed()已经丢失了小数位。

解决方案是改用parseFloat()保留小数位:

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

推荐阅读