Calculate currency totals in a checkout or payment flow without floating-point rounding errors like 0.1 + 0.2 returning 0.30000000000000004
Perform calculations that require more than 15 significant digits, such as scientific or financial computations, without losing precision
Use trigonometric functions or logarithms at arbitrary precision in a JavaScript or Node.js application
JavaScript's built-in numbers have a precision limit. Any number with more than about 15 significant digits gets rounded, and some simple arithmetic produces unexpected results: 0.1 + 0.2 does not equal 0.3 in JavaScript. decimal.js is a library that solves this by providing an arbitrary-precision decimal type that can hold as many digits as needed and perform arithmetic without those rounding errors. You create a Decimal value by passing a number or string to the Decimal constructor. The library recommends using strings for anything with more than a few digits, because JavaScript may already lose precision when it parses a numeric literal. Once you have a Decimal, you can add, subtract, multiply, divide, and perform many other operations. The results are new Decimal values, the original is never modified. Methods can be chained, so a series of calculations can be written in one expression. The precision (number of significant digits to keep) and the rounding mode are configurable. You can create multiple Decimal constructors with different settings that operate independently, which is useful if different parts of a program need different levels of precision. The library includes trigonometric functions, logarithms, square roots, and power functions. It also handles hexadecimal, binary, and octal input and output. For a smaller build without the trigonometric functions, there is a companion package called decimal.js-light. decimal.js ships as both a regular JavaScript file and an ES module, so it works in browsers and in Node.js. It has no external dependencies and targets very old JavaScript environments (ECMAScript 3), making it compatible with a wide range of platforms. It includes a TypeScript declaration file for type-checked projects. The library is used internally by math.js, a larger mathematics library for JavaScript.
← mikemcl on gitmyhub — every repo by this author, as a profile.
Verify against the repo before relying on details.