sprintf-js vs d3-format vs mathjs vs numeral vs format-number vs accounting-js
JavaScript Number Formatting Libraries Comparison
1 Year
sprintf-jsd3-formatmathjsnumeralformat-numberaccounting-jsSimilar Packages:
What's JavaScript Number Formatting Libraries?

These libraries provide various functionalities for formatting numbers, currencies, and mathematical expressions in JavaScript applications. They cater to different needs such as financial calculations, data visualization, and general number formatting, making it easier for developers to present numerical data in a user-friendly manner. Each library has its unique features, design principles, and use cases, allowing developers to choose the most suitable one based on their specific requirements.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
sprintf-js64,686,9872,12139.9 kB68a year agoBSD-3-Clause
d3-format8,923,92463357.8 kB183 years agoISC
mathjs1,652,56514,6409.49 MB1385 days agoApache-2.0
numeral1,274,8429,693-3518 years agoMIT
format-number36,08951-68 years agoBSD-3-Clause
accounting-js29,431114-129 years agoMIT
Feature Comparison: sprintf-js vs d3-format vs mathjs vs numeral vs format-number vs accounting-js

Number Formatting

  • sprintf-js:

    Sprintf-js allows for formatted string output using a syntax similar to C's printf function. It is particularly useful for creating complex formatted strings that include numbers, providing flexibility in how numerical data is presented within strings.

  • d3-format:

    D3-format offers extensive formatting options tailored for data visualization, including support for scientific notation, percentages, and custom formats. It allows for precise control over how numbers are displayed in charts and graphs, catering specifically to the needs of data-driven applications.

  • mathjs:

    Mathjs includes number formatting as part of its broader mathematical capabilities. It allows for formatting numbers in various ways, including currency and percentage formats, while also supporting complex calculations and operations, making it a versatile choice for mathematical applications.

  • numeral:

    Numeral provides a rich set of formatting options for numbers, including currency, percentages, and custom formats. It is designed to handle internationalization, making it suitable for applications that need to present numbers in different locales consistently.

  • format-number:

    Format-number focuses on basic number formatting, providing options for decimal places and thousands separators. It is lightweight and easy to implement, making it suitable for simple projects that require basic formatting without additional complexity.

  • accounting-js:

    Accounting-js provides simple methods for formatting numbers and currencies, allowing developers to easily format values for display in financial applications. It supports customizable decimal and thousand separators, making it straightforward to present numerical data clearly.

Mathematical Operations

  • sprintf-js:

    Sprintf-js does not perform mathematical operations; it is focused on string formatting. It is useful for outputting formatted strings that may include results from calculations done elsewhere.

  • d3-format:

    D3-format does not include mathematical operations; it is strictly for formatting numbers in the context of data visualization. It is meant to complement libraries that handle calculations.

  • mathjs:

    Mathjs excels in mathematical operations, offering a wide range of functions for calculations, including algebra, calculus, and statistics. It is ideal for applications that require extensive mathematical capabilities alongside number formatting.

  • numeral:

    Numeral does not perform mathematical operations but focuses on formatting numbers. It is best used in scenarios where calculations are handled by other libraries.

  • format-number:

    Format-number is limited to formatting and does not support mathematical operations. It is designed for straightforward use cases where calculations are handled separately.

  • accounting-js:

    Accounting-js is primarily focused on formatting and does not provide advanced mathematical operations. It is best used in conjunction with other libraries for calculations.

Complexity and Learning Curve

  • sprintf-js:

    Sprintf-js has a familiar syntax for those with a background in C or similar languages, making it easy to learn for those users. However, it may require some adjustment for those unfamiliar with formatted string output.

  • d3-format:

    D3-format may have a steeper learning curve for those unfamiliar with D3.js, as it is designed to work within that ecosystem. Understanding D3.js concepts is essential for effective use.

  • mathjs:

    Mathjs has a moderate learning curve due to its extensive features and capabilities. Users may need time to familiarize themselves with its API and mathematical functions, but it is well-documented.

  • numeral:

    Numeral is easy to learn and implement, with a clear API for formatting numbers. It is suitable for developers looking for a quick solution without extensive setup.

  • format-number:

    Format-number is straightforward and easy to learn, making it suitable for beginners who need basic formatting capabilities without complexity.

  • accounting-js:

    Accounting-js has a low learning curve due to its simple API focused on formatting. It is easy to integrate and use for basic financial applications.

Localization Support

  • sprintf-js:

    Sprintf-js does not focus on localization; it is primarily concerned with string formatting. Developers may need to handle localization separately.

  • d3-format:

    D3-format supports locale-specific formatting, making it suitable for applications that need to present numbers according to regional conventions in data visualizations.

  • mathjs:

    Mathjs includes localization support for number formatting, allowing users to format numbers according to regional conventions, making it versatile for international applications.

  • numeral:

    Numeral excels in localization, providing extensive options for formatting numbers based on different locales, making it ideal for applications targeting international audiences.

  • format-number:

    Format-number offers limited localization features, primarily focusing on basic formatting without extensive support for different locales.

  • accounting-js:

    Accounting-js provides basic localization support for currency formatting, allowing developers to customize formats based on locale. However, it may not cover all localization needs comprehensively.

Extensibility

  • sprintf-js:

    Sprintf-js is not designed for extensibility; it focuses on string formatting and does not provide options for extending its functionality.

  • d3-format:

    D3-format is highly extensible and can be integrated into D3.js visualizations, allowing developers to create custom formats and extend its functionality as needed.

  • mathjs:

    Mathjs is highly extensible, allowing users to create custom functions and extend its capabilities. This makes it suitable for complex applications that require tailored mathematical solutions.

  • numeral:

    Numeral is somewhat extensible, allowing for custom formats, but it is primarily focused on the provided formatting options without extensive customization capabilities.

  • format-number:

    Format-number is not designed for extensibility; it provides basic formatting features without options for customization or extension.

  • accounting-js:

    Accounting-js is lightweight and does not offer extensive extensibility options. It is designed for specific use cases related to financial data formatting.

How to Choose: sprintf-js vs d3-format vs mathjs vs numeral vs format-number vs accounting-js
  • sprintf-js:

    Select sprintf-js if you are looking for a library that mimics the functionality of C-style string formatting. It is useful for creating formatted strings with numbers, allowing for precise control over the output format, making it ideal for applications that require detailed string manipulation.

  • d3-format:

    Select d3-format if you are working with data visualization in D3.js and require precise control over number formatting. It is designed to work seamlessly with D3.js, offering a powerful and flexible way to format numbers, including support for locale-specific formatting and custom formats for charts and graphs.

  • mathjs:

    Use mathjs if you require a comprehensive library for mathematical operations, including advanced calculations, units, and complex numbers. It offers extensive functionality beyond just formatting, making it ideal for applications that involve heavy mathematical computations and require a robust solution.

  • numeral:

    Choose numeral if you need a versatile library that provides a wide range of formatting options for numbers, currencies, and percentages. It is particularly useful for applications that require consistent number formatting across different locales and contexts, making it a good choice for international applications.

  • format-number:

    Opt for format-number if you need a straightforward library for formatting numbers with options for decimal places and thousands separators. It is lightweight and easy to use, making it suitable for simple applications where advanced features are not necessary.

  • accounting-js:

    Choose accounting-js if you need a simple and lightweight solution for formatting and manipulating currency values, especially for financial applications. It provides straightforward methods for currency formatting, number formatting, and basic arithmetic operations without the overhead of complex features.

README for sprintf-js

sprintf-js

Build Status NPM Version Dependency Status devDependency Status

sprintf-js is a complete open source JavaScript sprintf implementation for the browser and Node.js.

Note: as of v1.1.1 you might need some polyfills for older environments. See Support section below.

Usage

var sprintf = require('sprintf-js').sprintf,
    vsprintf = require('sprintf-js').vsprintf

sprintf('%2$s %3$s a %1$s', 'cracker', 'Polly', 'wants')
vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd'])

Installation

NPM

npm install sprintf-js

Bower

bower install sprintf

API

sprintf

Returns a formatted string:

string sprintf(string format, mixed arg1?, mixed arg2?, ...)

vsprintf

Same as sprintf except it takes an array of arguments, rather than a variable number of arguments:

string vsprintf(string format, array arguments?)

Format specification

The placeholders in the format string are marked by % and are followed by one or more of these elements, in this order:

  • An optional number followed by a $ sign that selects which argument index to use for the value. If not specified, arguments will be placed in the same order as the placeholders in the input string.
  • An optional + sign that forces to precede the result with a plus or minus sign on numeric values. By default, only the - sign is used on negative numbers.
  • An optional padding specifier that says what character to use for padding (if specified). Possible values are 0 or any other character preceded by a ' (single quote). The default is to pad with spaces.
  • An optional - sign, that causes sprintf to left-align the result of this placeholder. The default is to right-align the result.
  • An optional number, that says how many characters the result should have. If the value to be returned is shorter than this number, the result will be padded. When used with the j (JSON) type specifier, the padding length specifies the tab size used for indentation.
  • An optional precision modifier, consisting of a . (dot) followed by a number, that says how many digits should be displayed for floating point numbers. When used with the g type specifier, it specifies the number of significant digits. When used on a string, it causes the result to be truncated.
  • A type specifier that can be any of:
    • % — yields a literal % character
    • b — yields an integer as a binary number
    • c — yields an integer as the character with that ASCII value
    • d or i — yields an integer as a signed decimal number
    • e — yields a float using scientific notation
    • u — yields an integer as an unsigned decimal number
    • f — yields a float as is; see notes on precision above
    • g — yields a float as is; see notes on precision above
    • o — yields an integer as an octal number
    • s — yields a string as is
    • t — yields true or false
    • T — yields the type of the argument1
    • v — yields the primitive value of the specified argument
    • x — yields an integer as a hexadecimal number (lower-case)
    • X — yields an integer as a hexadecimal number (upper-case)
    • j — yields a JavaScript object or array as a JSON encoded string

Features

Argument swapping

You can also swap the arguments. That is, the order of the placeholders doesn't have to match the order of the arguments. You can do that by simply indicating in the format string which arguments the placeholders refer to:

sprintf('%2$s %3$s a %1$s', 'cracker', 'Polly', 'wants')

And, of course, you can repeat the placeholders without having to increase the number of arguments.

Named arguments

Format strings may contain replacement fields rather than positional placeholders. Instead of referring to a certain argument, you can now refer to a certain key within an object. Replacement fields are surrounded by rounded parentheses - ( and ) - and begin with a keyword that refers to a key:

var user = {
    name: 'Dolly',
}
sprintf('Hello %(name)s', user) // Hello Dolly

Keywords in replacement fields can be optionally followed by any number of keywords or indexes:

var users = [
    {name: 'Dolly'},
    {name: 'Molly'},
    {name: 'Polly'},
]
sprintf('Hello %(users[0].name)s, %(users[1].name)s and %(users[2].name)s', {users: users}) // Hello Dolly, Molly and Polly

Note: mixing positional and named placeholders is not (yet) supported

Computed values

You can pass in a function as a dynamic value and it will be invoked (with no arguments) in order to compute the value on the fly.

sprintf('Current date and time: %s', function() { return new Date().toString() })

AngularJS

You can use sprintf and vsprintf (also aliased as fmt and vfmt respectively) in your AngularJS projects. See demo/.

Support

Node.js

sprintf-js runs in all active Node versions (4.x+).

Browser

sprintf-js should work in all modern browsers. As of v1.1.1, you might need polyfills for the following:

  • String.prototype.repeat() (any IE)
  • Array.isArray() (IE < 9)
  • Object.create() (IE < 9)

YMMV

License

sprintf-js is licensed under the terms of the BSD 3-Clause License.

Notes

1 sprintf doesn't use the typeof operator. As such, the value null is a null, an array is an array (not an object), a date value is a date etc.