Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 44 ยท Scales and Axes

Number and Time Formatting in D3

Format and parse values with d3.format specifiers (commas, SI prefixes, percent, currency), d3.timeFormat and utcFormat, d3.timeParse.

Labels such as 1234567.891 or Tue Mar 04 2025 00:00:00 GMT are unreadable in a chart. D3 includes two small formatting modules: d3-format turns numbers into text (1.2M, 45.6%, $1,234) and d3-time-format converts dates to and from text (Mar 2025). They plug straight into axes through tickFormat, and into tooltips and labels through .text(...).

d3.format: number specifiers

d3.format(specifier) returns a function. The specifier is a compact mini-language: [[fill]align][sign][symbol][0][width][,][.precision][~][type]. You rarely use all parts; a few combinations cover nearly everything.

JavaScript
const f = d3.format(",.2f");
f(1234567.891);     // "1,234,567.89"
Specifier Example input Output Meaning
, 1234567 1,234,567 thousands separator
.2f 3.14159 3.14 fixed, 2 decimals
,.2f 1234.5 1,234.50 both
.1% 0.456 45.6% percent (multiplies by 100)
.0% 0.456 46% percent, no decimals
~s 1500000 1.5M SI prefix, trailing zeros trimmed
.3s 1234 1.23k SI prefix with 3 significant digits
$,.2f 1234.5 $1,234.50 currency symbol
+.1f 3 +3.0 always show sign
05d 42 00042 zero-padded integer, width 5
x, b, o 255 ff, 11111111, 377 hex, binary, octal
e 12345 1.234500e+4 exponent notation

The ~ trims insignificant trailing zeros: d3.format(".2~f")(3) gives 3, not 3.00. And d3.format("~s") is the go-to formatter for large values on an axis.

d3.format in action

Notice how ~s formats 0.00042 as 420ยต: SI prefixes also work for small numbers. If you need only the formatted text and not a reusable function, d3.format(spec)(value) is fine; for performance, create the formatter once and reuse it.

Related helpers: d3.formatPrefix(",.0", 1e6) forces a specific SI prefix, d3.precisionFixed, d3.precisionRound and d3.precisionPrefix compute the right precision for a given step, and scale.tickFormat(count, specifier) returns a formatter whose precision matches the ticks a scale produces.

d3.formatLocale

By default numbers use US conventions (1,234.5). d3.formatLocale builds formatters for another locale, giving you control over the decimal mark, the thousands separator, grouping and the currency symbol:

JavaScript
const de = d3.formatLocale({
  decimal: ",", thousands: ".", grouping: [3], currency: ["", " โ‚ฌ"]
});
de.format(",.2f")(1234567.891);   // "1.234.567,89"

You can set a default for all calls with d3.formatDefaultLocale(definition). For ordinary pages, the browser's built-in Intl.NumberFormat is an alternative when you do not need D3's mini-language.

d3.timeFormat and d3.utcFormat

Dates use a strftime-style format string with percent directives. d3.timeFormat formats in the local time zone; d3.utcFormat in UTC (prefer it when your data is stored in UTC, so labels do not depend on the viewer's time zone).

Directive Meaning Example
%Y year, four digits 2025
%y year, two digits 25
%m month number 03
%B / %b full / short month name March / Mar
%d day of month, zero padded 04
%e day, space padded " 4"
%A / %a full / short weekday Tuesday / Tue
%H, %I hour 24h / 12h 14 / 02
%M, %S minute, second 05, 09
%p AM or PM PM
%j day of year 063
%U week of year 09
%Z time zone offset +0100
%L milliseconds 120
%x, %X, %c locale date, time, date and time -
Formatting and parsing dates

The - flag (%-d) removes the padding, so 4 instead of 04. Parsing returns null when the text does not match the format; check for it after parsing a file. Parsers are the counterpart of formatters: d3.timeParse for local time, d3.utcParse for UTC, d3.isoParse and d3.isoFormat for ISO 8601.

Multi-scale tick formats

Time axes show different labels depending on the level: a month name for month starts, a year for January, a day for a normal day. D3's time scales do this automatically through scale.tickFormat(); you get it for free with d3.axisBottom(timeScale). If you want to roll your own, write a function that picks a format by checking whether the date lies on a boundary of a time interval.

Time intervals

d3.timeDay, timeWeek, timeMonth, timeYear, timeHour, timeMinute and the UTC versions (utcDay and so on) are interval objects with methods such as:

  • interval.floor(date), ceil, round: snap to the boundary.
  • interval.offset(date, n): add n intervals.
  • interval.range(start, stop): a list of boundary dates (a tick source).
  • interval.every(k): every kth boundary, used in axis.ticks(d3.timeMonth.every(3)).
  • interval.count(a, b): how many boundaries lie between two dates.

Weekdays have named intervals: d3.timeMonday, timeSunday, utcFriday, and so on, useful for calendar charts.

Time intervals

Time zones are the usual source of "off by one day" bugs. A string like "2025-03-04" is parsed as UTC midnight by new Date, but by d3.timeParse as local midnight. Displaying it with the other kind of formatter can show March 3 for viewers west of Greenwich. Use matching pairs: utcParse with utcFormat, timeParse with timeFormat.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does d3.format('.1%')(0.456) return?

    The percent type multiplies by 100 and .1 keeps one decimal digit, giving 45.6%.
  2. 2. Which specifier is a good default for large axis values such as 1500000?

    The s type uses SI prefixes and ~ trims trailing zeros, so the axis stays compact.
  3. 3. What does d3.utcParse('%d/%m/%Y')('not a date') return?

    Parsers return null for input that does not match the format, so you can filter bad rows.
  4. 4. Why pair utcParse with utcFormat?

    Local and UTC functions interpret the same instant differently. Use matching pairs for consistent labels.
  5. 5. What does d3.utcMonth.floor(date) do?

    floor snaps to the previous interval boundary; round picks the nearest; ceil picks the next.

Summary

  • d3.format builds number formatters from a mini-language: , separators, .2f, %, ~s for SI, $ for currency.
  • d3.timeFormat and d3.utcFormat print dates with % directives; timeParse and utcParse read them (returning null on failure).
  • Time intervals (utcDay, timeMonth, ...) offer floor, ceil, offset, range, every and count.
  • Use matching local or UTC pairs, and reuse formatter functions instead of creating them in loops.

Next: Building Bar Charts