jQuery sum table toFixed 无法正常工作
jQuery sum table toFixed not working properly
我有动态 table 数据,可以采用不同的格式。例如:500 500,57 1500,00 1.500,00。
目前我正在做 str_replace 以删除千分之一的第一个点,然后用点替换逗号。
echo str_replace(array(".", ",",), array("", "."), $row['rad_iznos']);
效果很好,我只得到千分之一的小数点分隔符。但是当我使用
总和的 toFixed(2) 选项 decimal 的值被留下,它应该根据这个工作: 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 不见了,我只是不明白它背后的逻辑。请指教。千分之一的值是正确的。
问题不在于 .toFixed()
,而在于:
totals[i] += parseInt($(this).html());
这会将每行的值作为整数相加 - 因此会丢失小数位,因此当它到达 .toFixed()
时它已经丢失了小数位。
解决办法是改用parseFloat()
,保留小数位:
totals[i] += parseFloat($(this).html());
我有动态 table 数据,可以采用不同的格式。例如:500 500,57 1500,00 1.500,00。 目前我正在做 str_replace 以删除千分之一的第一个点,然后用点替换逗号。
echo str_replace(array(".", ",",), array("", "."), $row['rad_iznos']);
效果很好,我只得到千分之一的小数点分隔符。但是当我使用 总和的 toFixed(2) 选项 decimal 的值被留下,它应该根据这个工作: 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>');
});
});
您可以在此处查看示例:
问题不在于 .toFixed()
,而在于:
totals[i] += parseInt($(this).html());
这会将每行的值作为整数相加 - 因此会丢失小数位,因此当它到达 .toFixed()
时它已经丢失了小数位。
解决办法是改用parseFloat()
,保留小数位:
totals[i] += parseFloat($(this).html());