問題描述
在 D3 中用逗號格式化數字 (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.
‑‑‑‑‑
參考解法
方法 1:
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
方法 2:
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
方法 3:
To save you from reading @altocumulus' comments, this is the correct answer:
let format = d3.format(','); let formattedX = format(x);
From the docs:
The comma (
,
) option enables the use of a group separator, such as a comma for thousands.
<p>(@altocumulus gets all the credit.)</p>