5

I am writing a jsx file and want to format the display of numbers in a table. Here is the code for the table:

<tr>
  <td>
    {stringVar}
  </td>
  <td>
    {numberVar}
  </td>
</tr>

The numberVar is being printed directly; how can I display that number with C-style string formatting (I need to set precision value, add commas, and a $ character)?

Dmitry Shvedov
  • 3,169
  • 4
  • 39
  • 51
Eric Baldwin
  • 3,341
  • 10
  • 31
  • 71
  • This is just JavaScript -- so you can use anything that works in Javascript: http://stackoverflow.com/questions/9318674/javascript-number-currency-formatting – WiredPrairie Mar 28 '15 at 20:29
  • I'm a big fan of using Mout (http://moutjs.com/docs/latest/) for this. It's not a library, just a collection of utility modules. See http://moutjs.com/docs/latest/number.html#currencyFormat and http://moutjs.com/docs/latest/number.html#enforcePrecision. – Chris Houghton Mar 30 '15 at 08:31

1 Answers1

7

You can use any JS expression to format the value. A popular number formatting library is http://numeraljs.com/ but there are many others of course.

As for prefixing it with $, that's just string concatenation:

{"$" + numberVar}

Or, using string interpolation ES6 syntax :

{`$ ${numberVar}`}
Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
  • numeraljs is not supported anymore and breaks with react native (I think because of babel). Use [numbrojs](http://numbrojs.com/) instead – amirfl Jul 27 '16 at 19:26