Ag-Grid: Number Formatting eg:123456.78 to 123,457

后端 未结 3 1409
情歌与酒
情歌与酒 2021-02-13 09:40

I have huge sets of numeric data. this needs to be rendered as comma separated value. For Ex. 123456.78 to be rendered as 123,457 using Ag-Grid. Kindl

3条回答
  •  甜味超标
    2021-02-13 10:06

    As per the cell rendering flow documentation (here), you can use the colDef.valueFormatter, like this:

        var columnDefs = [
            {headerName: "Number", field: "number"},
            {headerName: "Formatted", field: "number", valueFormatter: currencyFormatter}
        ];
        
        function currencyFormatter(params) {
            return '£' + formatNumber(params.value);
        }
        
        function formatNumber(number) {
            // this puts commas into the number eg 1000 goes to 1,000,
            // i pulled this from stack overflow, i have no idea how it works
            return Math.floor(number).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
        }
    

    You could also use a cellRenderer as other posts describe, but that's typically for more complex rendering, whereas the valueFormatter is specifically for this case. From the ag-grid documentation:

    valueFormatter's are for text formatting. cellRenderer's are for when you want to include HTML markup and potentially functionality to the cell. So for example, if you want to put punctuation into a value, use a valueFormatter, if you want to put buttons or HTML links use a cellRenderer. It is possible to use a combination of both, in which case the result of the valueFormatter will be passed to the cellRenderer.

提交回复
热议问题