d3-format
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
d3-format is a JavaScript library designed to format numbers for human consumption. It addresses common issues encountered when using JavaScript to display numbers, like unexpected floating point results. Beyond fixing those issues, it also provides the ability to customize number formatting for various purposes, such as consistent formatting in tables for easy comparison, usage of grouped digits for large numbers, fixed precision for currencies, and many more. It can accommodate different localizations and standards, ensuring the numbers are displayed appropriately for different regions around the world. The library is influenced by Python 3's String format specification mini-language, providing a comprehensive and versatile approach for number management.
To use d3-format, you first need to install it via npm using the command npm install d3-format
. Once installed, the d3-format library allows you to create formatting functions that can be applied to numbers for display. Below are some example usages:
const d3 = require('d3-format');
const f = d3.format(".1f");
for (let i = 0; i < 10; ++i) {
console.log(f(0.1 * i)); // formats to 1 decimal place
}
console.log(d3.format(".0%")(0.123)); // rounded percentage, "12%"
console.log(d3.format("($.2f")(-3.5)); // localized fixed-point currency, "($3.50)"
console.log(d3.format("+20")(42)); // space-filled and signed, " +42"
console.log(d3.format(".^20")(42)); // dot-filled and centered, ".........42........."
console.log(d3.format(".2s")(42e6)); // SI-prefix with two significant digits, "42M"
console.log(d3.format("#x")(48879)); // prefixed lowercase hexadecimal, "0xbeef"
console.log(d3.format(",.2r")(4223)); // grouped thousands with two significant digits, "4,200"
You can also use d3-format in the browser, using the script tags to import it from CDNs such as Skypack or jsDelivr. Furthermore, you can set different locales by loading locale files provided with the package.
The documentation for d3-format is available in the README of its GitHub repository. The readme file includes a thorough explanation of installing the library, its methods, and parameters. It includes several examples on how to use these methods as well. It also guides you on how to customise your number formatting according to your needs, and work with different locales. For a detailed specification on the format specifier mini-language, you should refer to the *locale*.format
section.