javascript - 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>');
});
});
解决方案
问题不在于,.toFixed()
而是在于:
totals[i] += parseInt($(this).html());
这会将每一行的值添加为整数 - 因此会丢失小数位,所以当它到达时.toFixed()
已经丢失了小数位。
解决方案是改用parseFloat()
保留小数位:
totals[i] += parseFloat($(this).html());
推荐阅读
- css - Flexbox 响应式最后一列浮动和堆叠
- python-3.x - 在 python3 中使用 luigi.LocalTarget 和 PdfPages
- google-chrome-extension - 到达特定时间后自动发送按钮点击特定页面的 Chrome 扩展程序
- variables - awk -v,只打印整个变量的一个单词
- graphql - Apollo codegen 冗余类型
- postgresql - 如何使用 ldaptls=1 设置 Postgresql LDAP Auth。(PostgreSQL 10)
- html - how do I center the content of s router-outlet
- javascript - 如何在Javascript中添加/删除一行?
- javascript - js获取表单输入数组的索引
- javascript - 如何使用 jquery 创建测验结果