Search code examples
javascriptstring-formattingnumeral.js

Is there a format for numeral.js that will show decimals only when needed?


tests: http://jsfiddle.net/su918rLv/

This is the how the existing formats work:

numeral(1234.567).format('0,0');
//output: 1,235

numeral(1234.567).format('0,0.00');
//output: 1,234.57    

numeral(1234).format('0,0.00');
//output: 1,234.00

Is there a format that will produce both a whole number or decimal number based on the number value? I'm using 0,0.99 here but it is not the answer.

numeral(1234).format('0,0.99');
//output: 1,234

numeral(1234.567).format('0,0.99');
//output: 1,234.57

Solution

  • Yes. Put the optional decimals in brackets:

    numeral(1234).format('0,0.[00]');
    // output: 1,234
    
    numeral(1234.567).format('0,0.[00]');
    // output: 1,234.57