An arbitrary-precision Decimal type for JavaScript
open sourceMITself-hostablefree
decimal.js gives JavaScript an arbitrary-precision Decimal type, so 0.3 - 0.1 comes out as exactly 0.2 instead of suffering binary floating-point error. Precision is set in significant digits and every operation is rounded to it with a chosen rounding mode, as in Python's decimal module; it replicates most of Number.prototype and Math, adds trigonometric functions, non-integer powers and toFraction, and accepts hexadecimal, binary and octal values. It has no dependencies, ships as one script or an ES module with a TypeScript declaration file, and math.js uses it under the hood. Its author also maintains the smaller bignumber.js and big.js, and decimal.js-light, which drops the trigonometric functions.
Problems it solves
- 0.1 + 0.2 isn't 0.3 in JavaScript and my order totals are off by a cent
- do exact decimal math for prices, taxes and invoices in the browser
- calculate with numbers too big or too precise for a JavaScript Number without losing digits
- control the rounding mode and precision of financial calculations in Node.js
- compute square roots, powers and logarithms to 50 significant digits
- sine, cosine and other trig functions with arbitrary precision in JS
- turn a decimal result into a fraction like 355/113
- parse hexadecimal or binary strings with fractional parts into exact numbers
- use different precision settings for different calculations in the same app
- a big-number type with no dependencies that runs even in very old JavaScript engines
Features
- arbitrary-precision integers and decimals
- precision in significant digits with configurable rounding modes
- most Number.prototype and Math methods
- trigonometric, exponential and logarithmic functions
- non-integer powers and square roots
- toFraction with an optional maximum denominator
- hexadecimal, binary and octal input and output
- independent Decimal constructors with their own settings
- immutable values with chainable methods
- no dependencies; ECMAScript 3 only
View 1 more
- script file and ES module, with a TypeScript declaration file
Capabilities
| Has an API | plan not known |
|---|