FormidableLabs/d3-format

Name: d3-format

Owner: Formidable

Description: Format numbers for human consumption.

Forked from: d3/d3-format

Created: 2015-08-11 00:22:32.0

Updated: 2015-08-11 00:22:33.0

Pushed: 2015-08-11 00:36:36.0

Homepage:

Size: 201

Language: JavaScript

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

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:

(var i = 0; i < 10; i++) {
nsole.log(.1 * i);

And you got this:




000000000000004


00000000000001
00000000000001


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:

f = format(".1f");
(var i = 0; i < 10; i++) {
nsole.log(f(.1 * i));

Now you get this:











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

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

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

Installing

If you use NPM, npm install d3-format. Otherwise, download the latest release.

API Reference

# format(specifier)

An alias for locale.format on the default U.S. English locale. Use localeFormat for a different built-in locale or to define a new locale.

# formatPrefix(specifier, value)

An alias for locale.formatPrefix on the default U.S. English locale. Use localeFormat for a different built-in locale or to define a new 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:

ill]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:

The sign can be:

The symbol can be:

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, X and c). See precisionFixed and precisionRound for help picking an appropriate precision.

The available type values are:

The type n is also supported as 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:

at(".2")(42);  // "42"
at(".2")(4.2); // "4.2"
at(".1")(42);  // "4e+1"
at(".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:

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:

f = formatPrefix(",.0", 1e-6);
0042); // "420µ"
042); // "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.

# localeFormat(definition)

Returns a locale object for the specified definition with locale.format and locale.formatPrefix methods. If definition is a string, it is the name of a built-in locale:

Otherwise, the locale definition must include the following properties:

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

# 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:


ill": " ",
lign": ">",
ign": "-",
ymbol": "",
ero": false,
idth": undefined,
omma": false,
recision": 6,
ype": "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:

s = formatSpecifier("f");
ecision = precisionFixed(.01);
f = format(s);
); // "42.00";

# 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:

p = precisionFixed(0.5),
f = format("." + p + "f");
;   // "1.0"
5); // "1.5"
;   // "2.0"

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

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

Note: for the % format type, subtract two:

p = Math.max(0, precisionFixed(0.05) - 2),
f = format("." + p + "%");
5); // "45%"
0); // "50%"
5); // "55%"

# 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:

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

# 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:

p = precisionRound(0.01, 1.01),
f = format("." + p + "r");
99); // "0.990"
0);  // "1.00"
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:

p = precisionRound(0.1, 1.1),
f = format("." + p + "r");
9); // "0.90"
0); // "1.0"
1); // "1.1"

Note: for the e format type, subtract one:

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

This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.