• Stars
    star
    611
  • Rank 70,481 (Top 2 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created almost 9 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Format numbers for human consumption.

d3-format

Ever noticed how sometimes JavaScript doesn’t display numbers the way you expect? Like, you tried to print tenths with a simple loop:

for (let i = 0; i < 10; ++i) {
  console.log(0.1 * i);
}

And you got this:

0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6000000000000001
0.7000000000000001
0.8
0.9

Welcome to binary floating point! ಠ_ಠ

Yet rounding error is not the only reason to customize number formatting. A table of numbers should be formatted consistently for comparison; above, 0.0 would be better than 0. Large numbers should have grouped digits (e.g., 42,000) or be in scientific or metric notation (4.2e+4, 42k). Currencies should have fixed precision ($3.50). Reported numerical results should be rounded to significant digits (4021 becomes 4000). Number formats should appropriate to the reader’s locale (42.000,00 or 42,000.00). The list goes on.

Formatting numbers for human consumption is the purpose of d3-format, which is modeled after Python 3’s format specification mini-language (PEP 3101). Revisiting the example above:

const f = d3.format(".1f");
for (let i = 0; i < 10; ++i) {
  console.log(f(0.1 * i));
}

Now you get this:

0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9

But d3-format is much more than an alias for number.toFixed! A few more examples:

d3.format(".0%")(0.123);  // rounded percentage, "12%"
d3.format("($.2f")(-3.5); // localized fixed-point currency, "(£3.50)"
d3.format("+20")(42);     // space-filled and signed, "                 +42"
d3.format(".^20")(42);    // dot-filled and centered, ".........42........."
d3.format(".2s")(42e6);   // SI-prefix with two significant digits, "42M"
d3.format("#x")(48879);   // prefixed lowercase hexadecimal, "0xbeef"
d3.format(",.2r")(4223);  // grouped thousands with two significant digits, "4,200"

See locale.format for a detailed specification, and try running d3.formatSpecifier on the above formats to decode their meaning.

Installing

If you use npm, npm install d3-format. You can also download the latest release on GitHub. In modern browsers, you can import d3-format from Skypack:

<script type="module">

import {format} from "https://cdn.skypack.dev/d3-format@3";

const f = format(".2s");

</script>

For legacy environments, you can load d3-format’s UMD bundle from an npm-based CDN such as jsDelivr; a d3 global is exported:

<script src="https://cdn.jsdelivr.net/npm/d3-format@3"></script>
<script>

var f = d3.format(".2s");

</script>

Locale files are published to npm and can be loaded using d3.json. For example, to set Russian as the default locale:

const locale = await d3.json("https://cdn.jsdelivr.net/npm/d3-format@3/locale/ru-RU.json");
d3.formatDefaultLocale(locale);
const f = d3.format("$,");
console.log(f(1234.56)); // 1 234,56 руб.

Try d3-format in your browser.

API Reference

# d3.format(specifier) <>

An alias for locale.format on the default locale.

# d3.formatPrefix(specifier, value) <>

An alias for locale.formatPrefix on the default locale.

# locale.format(specifier) <>

Returns a new format function for the given string specifier. The returned function takes a number as the only argument, and returns a string representing the formatted number. The general form of a specifier is:

[​[fill]align][sign][symbol][0][width][,][.precision][~][type]

The fill can be any character. The presence of a fill character is signaled by the align character following it, which must be one of the following:

  • > - Forces the field to be right-aligned within the available space. (Default behavior).
  • < - Forces the field to be left-aligned within the available space.
  • ^ - Forces the field to be centered within the available space.
  • = - like >, but with any sign and symbol to the left of any padding.

The sign can be:

  • - - nothing for zero or positive and a minus sign for negative. (Default behavior.)
  • + - a plus sign for zero or positive and a minus sign for negative.
  • ( - nothing for zero or positive and parentheses for negative.
  •   (space) - a space for zero or positive and a minus sign for negative.

The symbol can be:

  • $ - apply currency symbols per the locale definition.
  • # - for binary, octal, or hexadecimal notation, prefix by 0b, 0o, or 0x, respectively.

The zero (0) option enables zero-padding; this implicitly sets fill to 0 and align to =. The width defines the minimum field width; if not specified, then the width will be determined by the content. The comma (,) option enables the use of a group separator, such as a comma for thousands.

Depending on the type, the precision either indicates the number of digits that follow the decimal point (types f and %), or the number of significant digits (types , e, g, r, s and p). If the precision is not specified, it defaults to 6 for all types except (none), which defaults to 12. Precision is ignored for integer formats (types b, o, d, x, and X) and character data (type c). See precisionFixed and precisionRound for help picking an appropriate precision.

The ~ option trims insignificant trailing zeros across all format types. This is most commonly used in conjunction with types r, e, s and %. For example:

d3.format("s")(1500);  // "1.50000k"
d3.format("~s")(1500); // "1.5k"

The available type values are:

  • e - exponent notation.
  • f - fixed point notation.
  • g - either decimal or exponent notation, rounded to significant digits.
  • r - decimal notation, rounded to significant digits.
  • s - decimal notation with an SI prefix, rounded to significant digits.
  • % - multiply by 100, and then decimal notation with a percent sign.
  • p - multiply by 100, round to significant digits, and then decimal notation with a percent sign.
  • b - binary notation, rounded to integer.
  • o - octal notation, rounded to integer.
  • d - decimal notation, rounded to integer.
  • x - hexadecimal notation, using lower-case letters, rounded to integer.
  • X - hexadecimal notation, using upper-case letters, rounded to integer.
  • c - character data, for a string of text.

The type (none) is also supported as shorthand for ~g (with a default precision of 12 instead of 6), and the type n is shorthand for ,g. For the g, n and (none) types, decimal notation is used if the resulting string would have precision or fewer digits; otherwise, exponent notation is used. For example:

d3.format(".2")(42);  // "42"
d3.format(".2")(4.2); // "4.2"
d3.format(".1")(42);  // "4e+1"
d3.format(".1")(4.2); // "4"

# locale.formatPrefix(specifier, value) <>

Equivalent to locale.format, except the returned function will convert values to the units of the appropriate SI prefix for the specified numeric reference value before formatting in fixed point notation. The following prefixes are supported:

  • y - yocto, 10⁻²⁴
  • z - zepto, 10⁻²¹
  • a - atto, 10⁻¹⁸
  • f - femto, 10⁻¹⁵
  • p - pico, 10⁻¹²
  • n - nano, 10⁻⁹
  • µ - micro, 10⁻⁶
  • m - milli, 10⁻³
  • (none) - 10⁰
  • k - kilo, 10³
  • M - mega, 10⁶
  • G - giga, 10⁹
  • T - tera, 10¹²
  • P - peta, 10¹⁵
  • E - exa, 10¹⁸
  • Z - zetta, 10²¹
  • Y - yotta, 10²⁴

Unlike locale.format with the s format type, this method returns a formatter with a consistent SI prefix, rather than computing the prefix dynamically for each number. In addition, the precision for the given specifier represents the number of digits past the decimal point (as with f fixed point notation), not the number of significant digits. For example:

const f = d3.formatPrefix(",.0", 1e-6);
f(0.00042); // "420µ"
f(0.0042); // "4,200µ"

This method is useful when formatting multiple numbers in the same units for easy comparison. See precisionPrefix for help picking an appropriate precision, and bl.ocks.org/9764126 for an example.

# d3.formatSpecifier(specifier) <>

Parses the specified specifier, returning an object with exposed fields that correspond to the format specification mini-language and a toString method that reconstructs the specifier. For example, formatSpecifier("s") returns:

FormatSpecifier {
  "fill": " ",
  "align": ">",
  "sign": "-",
  "symbol": "",
  "zero": false,
  "width": undefined,
  "comma": false,
  "precision": undefined,
  "trim": false,
  "type": "s"
}

This method is useful for understanding how format specifiers are parsed and for deriving new specifiers. For example, you might compute an appropriate precision based on the numbers you want to format using precisionFixed and then create a new format:

const s = d3.formatSpecifier("f");
s.precision = d3.precisionFixed(0.01);
const f = d3.format(s);
f(42); // "42.00";

# new d3.FormatSpecifier(specifier) <>

Given the specified specifier object, returning an object with exposed fields that correspond to the format specification mini-language and a toString method that reconstructs the specifier. For example, new FormatSpecifier({type: "s"}) returns:

FormatSpecifier {
  "fill": " ",
  "align": ">",
  "sign": "-",
  "symbol": "",
  "zero": false,
  "width": undefined,
  "comma": false,
  "precision": undefined,
  "trim": false,
  "type": "s"
}

# d3.precisionFixed(step) <>

Returns a suggested decimal precision for fixed point notation given the specified numeric step value. The step represents the minimum absolute difference between values that will be formatted. (This assumes that the values to be formatted are also multiples of step.) For example, given the numbers 1, 1.5, and 2, the step should be 0.5 and the suggested precision is 1:

const p = d3.precisionFixed(0.5);
const f = d3.format("." + p + "f");
f(1);   // "1.0"
f(1.5); // "1.5"
f(2);   // "2.0"

Whereas for the numbers 1, 2 and 3, the step should be 1 and the suggested precision is 0:

const p = d3.precisionFixed(1);
const f = d3.format("." + p + "f");
f(1); // "1"
f(2); // "2"
f(3); // "3"

Note: for the % format type, subtract two:

const p = Math.max(0, d3.precisionFixed(0.05) - 2);
const f = d3.format("." + p + "%");
f(0.45); // "45%"
f(0.50); // "50%"
f(0.55); // "55%"

# d3.precisionPrefix(step, value) <>

Returns a suggested decimal precision for use with locale.formatPrefix given the specified numeric step and reference value. The step represents the minimum absolute difference between values that will be formatted, and value determines which SI prefix will be used. (This assumes that the values to be formatted are also multiples of step.) For example, given the numbers 1.1e6, 1.2e6, and 1.3e6, the step should be 1e5, the value could be 1.3e6, and the suggested precision is 1:

const p = d3.precisionPrefix(1e5, 1.3e6);
const f = d3.formatPrefix("." + p, 1.3e6);
f(1.1e6); // "1.1M"
f(1.2e6); // "1.2M"
f(1.3e6); // "1.3M"

# d3.precisionRound(step, max) <>

Returns a suggested decimal precision for format types that round to significant digits given the specified numeric step and max values. The step represents the minimum absolute difference between values that will be formatted, and the max represents the largest absolute value that will be formatted. (This assumes that the values to be formatted are also multiples of step.) For example, given the numbers 0.99, 1.0, and 1.01, the step should be 0.01, the max should be 1.01, and the suggested precision is 3:

const p = d3.precisionRound(0.01, 1.01);
const f = d3.format("." + p + "r");
f(0.99); // "0.990"
f(1.0);  // "1.00"
f(1.01); // "1.01"

Whereas for the numbers 0.9, 1.0, and 1.1, the step should be 0.1, the max should be 1.1, and the suggested precision is 2:

const p = d3.precisionRound(0.1, 1.1);
const f = d3.format("." + p + "r");
f(0.9); // "0.90"
f(1.0); // "1.0"
f(1.1); // "1.1"

Note: for the e format type, subtract one:

const p = Math.max(0, d3.precisionRound(0.01, 1.01) - 1);
const f = d3.format("." + p + "e");
f(0.01); // "1.00e-2"
f(1.01); // "1.01e+0"

Locales

# d3.formatLocale(definition) <>

Returns a locale object for the specified definition with locale.format and locale.formatPrefix methods. The definition must include the following properties:

  • decimal - the decimal point (e.g., ".").
  • thousands - the group separator (e.g., ",").
  • grouping - the array of group sizes (e.g., [3]), cycled as needed.
  • currency - the currency prefix and suffix (e.g., ["$", ""]).
  • numerals - optional; an array of ten strings to replace the numerals 0-9.
  • percent - optional; the percent sign (defaults to "%").
  • minus - optional; the minus sign (defaults to "−").
  • nan - optional; the not-a-number value (defaults "NaN").

Note that the thousands property is a misnomer, as the grouping definition allows groups other than thousands.

# d3.formatDefaultLocale(definition) <>

Equivalent to d3.formatLocale, except it also redefines d3.format and d3.formatPrefix to the new locale’s locale.format and locale.formatPrefix. If you do not set a default locale, it defaults to U.S. English.

More Repositories

1

d3

Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript
106,311
star
2

d3-shape

Graphical primitives for visualization, such as lines and areas.
JavaScript
2,458
star
3

d3-plugins

[DEPRECATED] A repository for sharing D3.js V3 plugins.
JavaScript
1,808
star
4

d3-force

Force-directed graph layout using velocity Verlet integration.
JavaScript
1,702
star
5

d3-scale

Encodings that map abstract data to visual representation.
JavaScript
1,567
star
6

d3-queue

Evaluate asynchronous tasks with configurable concurrency.
JavaScript
1,411
star
7

d3-hierarchy

2D layout algorithms for visualizing hierarchical data.
JavaScript
1,064
star
8

d3-geo-projection

Extended geographic projections for d3-geo.
JavaScript
1,058
star
9

d3-geo

Geographic projections, spherical shapes and spherical trigonometry.
JavaScript
988
star
10

d3-scale-chromatic

Sequential, diverging and categorical color scales.
JavaScript
787
star
11

d3-sankey

Visualize flow between nodes in a directed acyclic network.
JavaScript
763
star
12

d3-ease

Easing functions for smooth animation.
JavaScript
604
star
13

d3-delaunay

Compute the Voronoi diagram of a set of two-dimensional points.
JavaScript
588
star
14

d3-selection

Transform the DOM by selecting elements and joining to data.
JavaScript
547
star
15

d3-zoom

Pan and zoom SVG, HTML or Canvas using mouse or touch input.
JavaScript
495
star
16

d3-contour

Compute contour polygons using marching squares.
JavaScript
487
star
17

d3-interpolate

Interpolate numbers, colors, strings, arrays, objects, whatever!
JavaScript
482
star
18

d3-array

Array manipulation, ordering, searching, summarizing, etc.
JavaScript
452
star
19

d3-dsv

A parser and formatter for delimiter-separated values, such as CSV and TSV.
JavaScript
416
star
20

d3-color

Color spaces! RGB, HSL, Cubehelix, CIELAB, and more.
JavaScript
389
star
21

d3-drag

Drag and drop SVG, HTML or Canvas using mouse or touch input.
JavaScript
328
star
22

d3-time-format

Parse and format times, inspired by strptime and strftime.
JavaScript
324
star
23

d3-voronoi

Compute the Voronoi diagram of a set of two-dimensional points.
JavaScript
250
star
24

d3-hexbin

Group two-dimensional points into hexagonal bins.
JavaScript
231
star
25

d3-time

A calculator for humanity’s peculiar conventions of time.
JavaScript
227
star
26

d3-quadtree

Two-dimensional recursive spatial subdivision.
JavaScript
225
star
27

d3-transition

Animated transitions for D3 selections.
JavaScript
219
star
28

d3-fetch

Convenient parsing for Fetch.
JavaScript
215
star
29

d3-axis

Human-readable reference marks for scales.
JavaScript
204
star
30

d3.github.com

The D3 website.
JavaScript
195
star
31

d3-path

Serialize Canvas path commands to SVG.
JavaScript
192
star
32

d3-timer

An efficient queue for managing thousands of concurrent animations.
JavaScript
159
star
33

d3-brush

Select a one- or two-dimensional region using the mouse or touch.
JavaScript
154
star
34

d3-3.x-api-reference

An archive of the D3 3.x API Reference.
153
star
35

d3-random

Generate random numbers from various distributions.
JavaScript
136
star
36

d3-chord

Visualizations relationships or network flow with a circular layout.
JavaScript
122
star
37

d3-tile

Compute the quadtree tiles to display in a rectangular viewport.
JavaScript
120
star
38

d3-collection

Handy data structures for elements keyed by string.
JavaScript
111
star
39

d3-request

A convenient alternative to XMLHttpRequest.
JavaScript
109
star
40

d3-geo-polygon

Clipping and geometric operations for spherical polygons.
JavaScript
102
star
41

d3-polygon

Geometric operations for two-dimensional polygons.
JavaScript
97
star
42

d3-require

A minimal, promise-based implementation to require asynchronous module definitions.
JavaScript
78
star
43

d3-selection-multi

Multi-value syntax for d3-selection and d3-transition.
JavaScript
75
star
44

d3-dispatch

Register named callbacks and call them with arguments.
JavaScript
75
star
45

versor

a home for Mike Bostock's versor.js
JavaScript
34
star
46

d3-bundler

DEPRECATED; use rollup/rollup.
JavaScript
34
star
47

d3-hsv

The HSV (Hue, Saturation, Value) color space.
JavaScript
26
star
48

d3-logo

D3 brand assets.
23
star
49

d3-cam16

A d3 implementation of the CIECAM16 color appearance model.
JavaScript
22
star
50

d3-hcg

The HCG (Hue, Chroma, Grayness) color space derived from the Munsell color system.
JavaScript
20
star
51

d3-scripts

Common scripts for D3 modules.
JavaScript
15
star
52

d3-hull

DEPRECATED; see d3-polygon’s hull function.
JavaScript
14
star
53

blur-benchmark

temporary benchmark for d3.blur implementations
JavaScript
2
star