Ignore Zero When Rendering a Number in Money Format

Ignore Zero When Rendering a Number in Money Format

Ninja JoeNinja Joe Posts: 10Questions: 4Answers: 1

To display currency, I am using:

columnDefs: [
{ targets: [ 1 ], render: $.fn.dataTable.render.number( ',', '.', 2, '$','' ) },
],

It works great! My numbers are displayed as $136,029.14.

However, when a number is 0, I want to show my users 0, not $0.00. How can I modify my code in columnDefs to do that? My first thought was a ternary statement but without knowing the value of the cell, I am unsure how to proceed.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 15,787Questions: 25Answers: 3,739
    Answer ✓

    Use columns.render. The number renderer, $.fn.dataTable.render.number, can take an additional API display(). Something like this should work:

    columnDefs: [
      { targets: [ 1 ], 
        render: function (data, type, row) {
          return data === 0 ? 0 : $.fn.dataTable.render.number( ',', '.', 2, '$','' ).display( data );
      }
    ],
    

    Didn't test this code so hopefully its close enough to make work :smile:

    Kevin

  • Ninja JoeNinja Joe Posts: 10Questions: 4Answers: 1

    Thank you, kthorngren. Your suggestion worked, WITH some modifications. Here's the final code I ended up using, hopefully it helps someone in the future:

    $( '#certificates-datatable' ).DataTable( { scrollX: true, pageLength: 50, pagingType: 'full_numbers', 'order': [ [ 4, 'desc' ] ],
    columnDefs: [
    { targets: [ 1 ], render: function( data, type, row ) {
    return ( data === '0' || data === '0.00' ) ? '0' : $.fn.dataTable.render.number( ',', '.', 2, '$', '' ).display( data ) }
    },
    ]
    } );

  • allanallan Posts: 55,865Questions: 1Answers: 8,830 Site admin

    I think this is a really good point actually. I think this is something that should be built into the number renderer. I'll add that for the next release.

    Allan

Sign In or Register to comment.