liveBook · Manning

D3.format()

As explained in D3.js in Action, Third Edition

d3.format() is a D3-format function that creates a formatter for converting numeric values into strings according to a specified format.

d3.format() creates a formatter that converts numeric values into strings according to a format specification. Call it with a specification, then call the returned formatter with a number. section 4.4.3

Common visualization uses include:

  • Format a ratio as a rounded percentage with d3.format(".0%"). section 5.1.4
  • Limit a tooltip value to three digits with d3.format(".3"). section 7.3.1
  • Display large values with three significant digits and a suffix such as M by using d3-format's ".3s" specification. section 11.2.3

Formatting an arc label

Calculate the arc's percentage and pass it to the formatter when setting a text element: .text(d => d3.format(".0%")(d.percentage)). The result is a rounded number with a percent sign, suitable for a donut or arc label. section 5.1.4

Formatting a tooltip

Set a tooltip's text from the hovered datum with .text(`${d3.format(".3")(d.avg_temp_F)}°F`). Formatting keeps the displayed temperature concise while the tooltip is positioned above the pointed circle. section 7.3.1

How D3.js in Action, Third Edition covers it

How deep it goes
Demonstrates percentage, precision, significant-digit, and suffix formats through chart labels and tooltips, while deferring the complete format specification list.
Examples
Uses precipitation percentages, donut-chart ratios, Fahrenheit temperatures, and language speaker counts as formatted outputs.
What it assumes
Assumes basic D3 selections, bound data, callbacks, and SVG text elements while teaching format specifications through working visualizations.
What you can do after
Apply it via D3 to produce readable percentage labels, concise tooltip values, and abbreviated large-number displays.
How it connects
Connects numeric formatting with D3 data binding, arc generators, donut charts, tooltips, and interactive visualizations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.