如何为Tabulator表格单元格添加百分号
解决方案:在Tabulator中显示百分比且保留数值排序能力
直接利用Tabulator的列格式化(formatter)功能,既实现前端显示百分比,又不修改原始数字数据,完美保留排序功能:
修改你的表格列配置,给otperc列添加自定义格式化函数:
function addTable(data) { var table = new Tabulator("#table", { height:205, data: data.rows, layout:"fitColumns", columns:[ {title:"Work Type", field:"WorkType"}, {title:"Total", field:"total"}, { title:"On Time", field:"otperc", // 自定义格式化函数,拼接百分号 formatter:function(cell, formatterParams, onRendered){ return cell.getValue() + "%"; } } ], }); }
原理说明
- 原始数据中的
otperc依然是数字类型(比如示例里的38、44),表格排序时会基于这些原始数值计算,完全不受影响。 - 格式化函数仅作用于前端显示层,把数字转成带百分号的字符串,不会改动数据源本身。
如果需要显示带小数的百分比(比如38.5%),可以调整格式化函数为:
formatter:function(cell){ return cell.getValue().toFixed(1) + "%"; }
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

