37

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
Homer
  • 7,594
  • 14
  • 69
  • 109

2 Answers2

58

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
idrosid
  • 7,983
  • 5
  • 44
  • 41
  • 2
    Thanks! It also works in [numbro.js](http://numbrojs.com/format.html): `numbro(1234).format('0,0.[00]')` and `numbro(1234.456).format('0,0.[00]')` – Homer Jul 06 '15 at 13:23
  • 1
    I have a related question but couldn't find an answer. What if I want to show all decimal places in tact based on the value? For example I want to show 1,234 and 1,234.56 and 1,234.567 respectively as it is – Bruce Sep 19 '16 at 09:15
  • 1
    @bruce: put as many optional places as you need. Eg. `0,0.[000000]` will format numbers with up to 6 decimal places if number has that many or more. – Robert Koritnik Oct 26 '16 at 13:43
  • @RobertKoritnik Thanks it makes sense, my mind was stuck when I asked that question XD – Bruce Oct 27 '16 at 03:42
  • Is there a way to optionally force two decimals for currency? I wouldn't want to display $100.1, for example. – johnwp Jun 22 '18 at 21:35
  • 4
    To optionally force two decimals for currency, `'$0,0[.]00'` works for me. – johnwp Jun 22 '18 at 21:40
  • Is there a place where I can see all the possible things I can do in the format string? – derickito Oct 24 '18 at 17:56
7

Either no decimals or 2 decimals:

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

numeral(1234.5).format('0,0[.]00');
// output: 1,234.50

(Based on johnwp's comment from the accepted answer).

Stuck
  • 11,225
  • 11
  • 59
  • 104