decimal128.js
, an NPM package for IEEE 754 Decimal128 floating-point decimal numbersI’m happy to announce decimal128.js
, an NPM package I made for simulating IEEE 754 Decimal128 numbers in JavaScript.
(This is my first NPM package. I made it in TypeScript; it’s my first go at the language.)
Decimal128 is an IEEE standard for floating-point decimal numbers. These numbers aren’t the binary floating-point numbers that you know and love (?), but decimal numbers. You know, the kind we learn about before we’re even ten years old. In the binary world, things like 0.1 + 0.2
aren’t exactly* equal to 0.3
, and calculations like 0.7 * 1.05
work out to exactly 0.735
. These kinds of numbers are what we use when doing all sorts of everyday calculations, especially those having to do with money.
Decimal128 encodes decimal numbers into 128 bits. It is a fixed-width encoding, unlike arbitrary-precision numbers, which, of course, require an arbitrary amount of space. The encoding can represent of numbers with up to 34 significant digits and an exponent of –6143 to 6144. That is a truly vast amount of space if one keeps the intended use cases involving human-readable and -writable numbers (read: money) in mind.
I’m working on extending the JavaScript language with decimal numbers (proposal-decimal). One of the design decisions that has to be made there is whether to implement arbitrary-precision decimal numbers or to implement some kind of approximation thereof, with Decimal128 being the main contender. As far as I could tell, there was no implementation of Decimal128 in JavaScript, so I made one.
The intention isn’t to support the full Decimal128 standard, nor should one expect to achieve the performance that, say, a C/C++ library would give you in userland JavaScript. (To say nothing of having machine-native decimal instructions, which is truly exotic.) The intention is to give JavaScript developers something that genuinely strives to approximate Decimal128 for JS programs.
In particular, the hope is that this library offers the JS community a chance to get a feel for what Decimal128 might be like.
Just do
$ npm install decimal128
and start using the provided Decimal128
class.
If you find any bugs or would like to request a feature, just open an issue and I’ll get on it.
Jesse Alama