When I create a chart with D3 the axis labels have commas in them to delimit thousands, millions, etc.
Is there a D3 function that I can call passing it a number and getting back a string formatted with commas like used in the axis? It would be the equivalent of this C#: x.ToString("0,000")
.
I know there exist libraries to do formatting like this, but I'd like to avoid including additional libraries. I'm using D3 already, so if there is an API in there I can use that would be great.
d3-format helps you format numbers for human consumption. The ~ option trims insignificant trailing zeros across format types. The empty type is also supported as shorthand for ~g (with a default precision of 12 instead of 6), and the type n is shorthand for , g .
The syntax for doing this has become more strictly enforced in d3 v4 but looks like:
format = d3.format(",");
formattedX = format(x);
D3 formatting docs
A quick search in the documentation found it:
format = d3.format("0,000");
formattedX = format(x);
https://github.com/mbostock/d3/wiki/Formatting#wiki-d3_format
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With