Skip to content

format

An extension to d3’s format function that adds more string formatting types and localizations.

".3~a" is the d3plus extension: it routes to formatAbbreviate, so large numbers get the k/M/B suffixes charts use and small fractions keep their significant digits. Compare d3’s own ".2s", which uses SI prefixes and rounds to two significant digits.

import {format} from "@d3plus/format";

format(".3~a")(1234567);
format(".3~a")(0.0042);
format(".3~a")(1234567890);
format(".2s")(1234567);

Takes a d3-format specifier and returns a formatting function: , groups thousands, .2f fixes two decimals, $ prefixes the locale currency, % scales by 100, 08 zero-pads to eight characters, and e switches to exponent notation.

import {format} from "@d3plus/format";

format(",.2f")(1234.567);
format("$,.0f")(1234567);
format(".1%")(0.256);
format("08.2f")(3.14159);
format(".2e")(123456);

The specifier is parsed once, so keep the returned function and apply it to every value, for instance as a chart’s tooltipConfig or axis tickFormat.

import {format} from "@d3plus/format";

const money = format("$,.2f");
money(19.99);
money(1500);
money(2500000);

Parameters

import {format} from "@d3plus/format";
specifierrequiredstring

The string specifier used by the format function.