Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting numbers with commas in D3

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.

like image 243
MattD Avatar asked Mar 04 '13 21:03

MattD


People also ask

What does d3 format do?

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 .


2 Answers

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

like image 128
me. Avatar answered Oct 07 '22 16:10

me.


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

like image 37
MattD Avatar answered Oct 07 '22 17:10

MattD