How to remove trailing zeros when formating numbers

How to remove trailing zeros when formating numbers

jstuardojstuardo Posts: 104Questions: 41Answers: 0

Hello...

To format a number in a column I use $.fn.dataTable.render.number('.', ',', 3, ''). That displays the number with 3 decimal places, however, when the number is integer, it is displayed with ".000". Is there a way to avoid this?

For example, if number 1.2345 is displayed, it should be shown as 1.234. If number 1.230 is displayed, it should be shown as 1.23 and finally, if number 1.000 is displayed, it should be shown as 1.

This can be done in other languages using the string format #,##0.### so I am wondering if DataTable allows to do that also.

Regards
Jaime

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,470 Site admin

    Hi Jaime,

    I'm afraid not - our number formatting isn't that smart. There isn't a way to remove the redundant 0s without having your own custom renderer. You could call our render and then modify the result:

    render: function (data) {
      let num = DataTable.render.number(null, null, 3, '').display(data);
    
      return num.replace(/0+$/, '');
    }
    

    Allan

  • jstuardojstuardo Posts: 104Questions: 41Answers: 0

    Thanks allan, however, your regex matches also the 0 in numbers like 120.

    Finally I did this and it worked:

        render: function (data, type, row) {
                            let value = $.fn.dataTable.render.number('.', ',', 3, '').display(data);
                            let result = value.match(/(?:(,\d*[1-9])|,)0+$/);
                            if (result && result.length > 0)
                                return value.replace(result[0], result[1] ? result[1] : '');
                            else
                                return value;
                        } 
    

    Maybe you could think about implementing this in a future release.

    Regards
    Jaime

  • allanallan Posts: 63,498Questions: 1Answers: 10,470 Site admin
    Answer ✓

    I should have thought of that! Good to hear you have a solution.

    More flexible formatting is indeed something I'd like to add in future :). Thanks for the feedback.

    Allan

Sign In or Register to comment.