1

I can display 1,500,000 as 1.5M using d3.format(".2s")(1500000), but how can I display 500,000 as .5M?

Using d3.format(".2s")(500000) results in 500k.

Also, d3.format(".2s")(5000000) results in 5.0M, but d3.format(".2s")(10000000) results in 10M. Is there a format I can specify to get both 5.0M and 10.0M?

nachocab
  • 13,328
  • 21
  • 91
  • 149

1 Answers1

2

The first isn't possible directly with D3. The idea of the SI prefix is that you always have a non-zero value in front of the point. Similarly, the second thing you're asking for isn't possible either, as the precision (the number after the dot in the format) has no effect when using SI formatting.

It sounds like the easiest thing to do in your case would be to create a millions formatter manually, i.e. divide all the numbers by a million and add the "M" at the end yourself. This would then allow you to use one of the other formatters that allows you to specify the precision.

You may also find the d3.formatPrefix() function useful, which will give you the SI prefix for a given number.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • I have a question here (http://stackoverflow.com/q/41385010/1735836) you might be able to help me with. – Patricia Dec 29 '16 at 18:09