Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
The d3-format package is part of the D3 (Data-Driven Documents) JavaScript library, which is used for producing graphical visualizations of data primarily on the web. The d3-format module provides a system for formatting numbers for human-readable display, allowing users to specify the appearance of numbers, such as the decimal precision, alignment, padding, rounding, and locale-specific formatting.
Number Formatting
This feature allows you to format numbers using a variety of options. The example shows formatting a number to two decimal places.
const d3 = require('d3-format');
const format = d3.format('.2f');
console.log(format(3.14159)); // Outputs: '3.14'
Locale-specific Formatting
This feature supports locale-specific formatting. The example demonstrates formatting a number as currency in a European style, using comma for decimal and period for thousands separator.
const d3 = require('d3-format');
const locale = d3.formatLocale({ decimal: ',', thousands: '.', grouping: [3], currency: ['€', ''] });
const format = locale.format('$,.2f');
console.log(format(1234567.89)); // Outputs: '€1.234.567,89'
SI Prefix Formatting
This feature allows formatting numbers with SI prefixes, useful for representing large or small numbers succinctly. The example formats the number 1500 with an SI prefix, resulting in '1.50k'.
const d3 = require('d3-format');
const format = d3.format('.3s');
console.log(format(1500)); // Outputs: '1.50k'
Numeral is another popular JavaScript library for formatting and manipulating numbers. It offers similar functionalities to d3-format, such as formatting numbers, currencies, percentages, and more. Compared to d3-format, Numeral might be considered more intuitive and easier to use for those not already using D3 for data visualization.
The accounting package is focused on formatting money and numbers for accounting purposes. It provides straightforward methods for formatting numbers as money or with custom precision, similar to d3-format but with a more specific focus on financial values. It is less flexible in general number formatting compared to 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 (var i = 0; i < 10; i++) {
console.log(.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! ಠ_ಠ
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 ↦ 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:
var f = format(".1f");
for (var i = 0; i < 10; i++) {
console.log(f(.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:
format(".0%")(.123); // rounded percentage, "12%"
format("$.2f")(3.5); // localized fixed-point currency, "£3.50"
format("+20")(42); // space-filled and signed, " +42"
format(".^20")(42); // dot-filled and centered, ".........42........."
format(".2s")(42e6); // SI-prefix with two significant digits, "42M"
format("#x")(48879); // prefixed lowercase hexadecimal, "0xbeef"
format(",.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.
If you use NPM, npm install d3-format
. Otherwise, download the latest release.
# format(specifier)
An alias for locale.format on the default locale. While this method generates output for U.S. English-speaking humans (en-US) by default, humans in other locales may be served using localeFormat or by editing index.js and rebuilding.
# formatPrefix(specifier, value)
An alias for locale.formatPrefix on the default locale. While this method generates output for U.S. English-speaking humans (en-US) by default, humans in other locales may be served using localeFormat or by editing index.js and rebuilding.
# locale.format(specifier)
Returns a new format function with 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 positive and a minus sign for negative. (Default behavior.)+
- a plus sign for positive and a minus sign for negative.
(space) - a space for 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
, X
and c
). See precisionFixed and precisionRound for help picking an appropriate precision.
The available type values are:
e
- exponent notation.f
- fixed point notation.g
- round to significant digits, and then either decimal or exponent notation.r
- round to significant digits, and then decimal notation.s
- round to significant digits, and then decimal notation with an SI prefix.%
- 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; ignores non-integers.o
- octal notation; ignores non-integers.d
- decimal notation; ignores non-integers.x
- hexadecimal notation, using lower-case letters; ignores non-integers.X
- hexadecimal notation, using upper-case letters; ignores non-integers.c
- converts the integer to the corresponding unicode character before printing.
(none) - like g
, but trim insignificant trailing zeros.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:
format(".2")(42); // "42"
format(".2")(4.2); // "4.2"
format(".1")(42); // "4e+1"
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:
var f = formatPrefix(",.0", 1e-6);
f(.00042); // "420µ"
f(.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.
# localeFormat(definition)
Returns a locale object for the specified definition, with locale.format and locale.formatPrefix methods. The locale 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., ["$", ""]
).(Note that the thousands property is a misnomer, as the grouping definition allows groups other than thousands.) The following locale definitions are available in the source:
To change the default locale, edit index.js and run npm run prepublish
.
# 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:
{
"fill": " ",
"align": ">",
"sign": "-",
"symbol": "",
"zero": false,
"width": undefined,
"comma": false,
"precision": 6,
"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:
var s = formatSpecifier("f");
s.precision = precisionFixed(.01);
var f = format(s);
f(42); // "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:
var p = precisionFixed(0.5),
f = 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:
var p = precisionFixed(1),
f = format("." + p + "f");
f(1); // "1"
f(2); // "2"
f(3); // "3"
Note: for the %
format type, subtract two:
var p = Math.max(0, precisionFixed(0.05) - 2),
f = format("." + p + "%");
f(.45); // "45%"
f(.50); // "50%"
f(.55); // "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:
var p = precisionPrefix(1e5, 1.3e6),
f = formatPrefix("." + p, 1.3e6);
f(1.1e6); // "1.1M"
f(1.2e6); // "1.2M"
f(1.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:
var p = precisionRound(0.01, 1.01),
f = 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:
var p = precisionRound(0.1, 1.1),
f = 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:
var p = Math.max(0, precisionRound(0.01, 1.01) - 1),
f = format("." + p + "e");
f(0.01); // "1.00e-2"
f(1.01); // "1.01e+0"
FAQs
Format numbers for human consumption.
The npm package d3-format receives a total of 4,368,124 weekly downloads. As such, d3-format popularity was classified as popular.
We found that d3-format demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.