JSFiddle - React, Tailwind, and code Playground
by Flexmonster Pivot Table
HTML
<script src="https://cdn.flexmonster.com/flexmonster.js"></script>
<button onclick="setMaxShortening('B')">1 B</button>
<button onclick="setMaxShortening('M')">1,000 M</button>
<button onclick="setMaxShortening('K')">1,000,000 K</button>
<div id="pivot-container"></div>
CSS
@import url(https://cdn.flexmonster.com/assets/jsfiddle-styles.css);
JavaScript
let pivot = new Flexmonster({
container: 'pivot-container',
componentFolder: 'https://cdn.flexmonster.com/',
toolbar: true,
customizeCell: customizeCellFunction,
report: {
dataSource: {
filename: 'data/data.json',
},
formats: [
{
name: '',
thousandsSeparator: ',',
decimalPlaces: 2,
},
],
slice: {
rows: [
{
uniqueName: 'Business Type',
},
{
uniqueName: '[Measures]',
},
],
columns: [
{
uniqueName: 'Color',
},
],
measures: [
{
uniqueName: 'revenue',
formula: 'sum("Price")*1000',
caption: 'revenue',
},
],
},
},
});
let maxShorteningLevel = 'B';
function setMaxShortening(v) {
maxShorteningLevel = v;
pivot.refresh(); // customizeCell will be called automatically when refrehsing the pivot
}
function customizeCellFunction(cell, data) {
if (data.type !== 'value' || data.value == null || isNaN(data.value)) return;
var v = Number(data.value);
var abs = Math.abs(v);
var formatted = null;
var allowB = maxShorteningLevel === 'B';
var allowM = maxShorteningLevel === 'B' || maxShorteningLevel === 'M';
var allowK = allowM || maxShorteningLevel === 'K';
if (allowB && abs >= 1_000_000_000) {
formatted = formatWithOptionalDecimals(v / 1_000_000_000) + ' B';
} else if (allowM && abs >= 1_000_000) {
formatted = formatWithOptionalDecimals(v / 1_000_000) + ' M';
} else if (allowK && abs >= 1_000) {
formatted = formatWithOptionalDecimals(v / 1_000) + ' K';
} else {
return;
}
cell.text = formatted;
data.label = formatted;
}
// helper: 0 decimals if integer, otherwise 2 decimals
function formatWithOptionalDecimals(num) {
var decimals = Number.isInteger(num) ? 0 : 2;
return num.toLocaleString("en-US", {
...