setting 2 decimal places in footer sum calculation for tabulator

20 Views Asked by At

In tablulator you can sum up the column into the footer of the table using column.bottomCalc = "sum";

However, when the column contains float values the sum total shows a really strange number of decimal places. How can this be restricted to 2 decimal places?

enter image description here

1

There are 1 best solutions below

0
Timur On

You can use the bottomCalcFormatter function to format the result to your requirements. See https://tabulator.info/docs/5.6/column-calcs#format

Below is an example where subtotal is rounded to 2 decimal places and total is fixed to always display 2 decimal places:

const tableData = [
  { id: 1, fullName: 'Oli Bob', sub: '12.25856', total: '125.54646' },
  { id: 2, fullName: 'Mary May', sub: '1.024565', total: '458.78666' },
  { id: 3, fullName: 'Christine Lobowski', sub: '42.994', total: '1548.4764654' },
  { id: 4, fullName: 'John Smith', sub: '30.5646456454', total: '5553.471213' },
  { id: 5, fullName: 'Tim Burton', sub: '51.8946', total: '6588.8' }
]

const table = new Tabulator('#table', {
  data: tableData,
  layout: 'fitDataFill',
  columns: [
    { title: 'Name', field: 'fullName' },
    {
      title: 'Subtotal',
      field: 'sub',
      bottomCalc: 'sum',
      bottomCalcFormatter: (cell, formatterParams, onRendered) => {
        // Round the result
        return Math.round((cell.getValue() + Number.EPSILON) * 100) / 100
      }
    },
    {
      title: 'Total',
      field: 'total',
      bottomCalc: 'sum',
      bottomCalcFormatter: (cell, formatterParams, onRendered) => {
        // Always display 2 decimal digits
        return cell.getValue().toFixed(2)
      }
    },
  ]
})
<!DOCTYPE html>
<html lang="en">

<head>
  <link href="https://unpkg.com/[email protected]/dist/css/tabulator.min.css" rel="stylesheet" />
  <script src="https://unpkg.com/[email protected]/dist/js/tabulator.min.js"></script>
</head>

<body>
  <div id="table"></div>
</body>

</html>