How do numbers show up automatically formatted and yet allow me to do comparisons in createdCell?

How do numbers show up automatically formatted and yet allow me to do comparisons in createdCell?

kimsiakimsia Posts: 14Questions: 0Answers: 0
edited March 2016 in Free community support

using latest stable which should be 1.10.11

I want numbers (positive or negative) (with decimals or no decimals) to auto be formatted as comma for delimiters and 2 decimal places.

E.g. if the json data is returning a 0, it will show up as 0.00

I also want to be able to compare the values of cellData inside createdCell function so I can choose to display colors.

Most likely red for the negative values.

I find it extremely difficult to do this.

If I use javascript formatter, they become string like.

var formatter = new Intl.NumberFormat('en-US', {

    minimumFractionDigits: 2,
});

And originally I did the formatting the moment I receive the data

"ajax": {
                "url": "/api/events.json?type=confirmed",
                "dataSrc": function ( response ) {
                    for (var i = 0; i < response.data.length; i++) {
                        response.data[i].start_date = moment(new Date(response.data[i].start_date)).format("MMM YYYY");
                     response.data[i].revenue = formatter.format(response.data[i].revenue);
                    
                    }
                    return response.data;
                },

Then I cannot compare easily in createdCell.

Please help.

Replies

  • kimsiakimsia Posts: 14Questions: 0Answers: 0

    inside the options

    "columnDefs": [ {
                    "targets": '_all',
                     "createdCell": function (td, cellData, rowData, row, col) {
                        if ( isNumeric(cellData) ) {
                            if ( cellData < 0) {
                                $(td).css('color', 'red');
                            }
                            $(td).html(formatter.format(cellData));
                        }
                    }
                } ],
    

    These are global functions/variables

    function isNumeric(n) {
      'use strict';
      n = String(n);
      n = n.replace(/\./g, '').replace(',', '');
      return !isNaN(parseFloat(n)) && isFinite(n);
    }
    
    var formatter = new Intl.NumberFormat('en-US', {
    
        minimumFractionDigits: 2,
    });
    

    I made it work using the above method. I hope there is a more "DataTables.Net" way of doing it.

This discussion has been closed.