Alec Wenzowski Alec Wenzowski -4 years ago 143
Javascript Question

Is there a Money class for JavaScript?

Disclaimer: complete rewrite for clarity as of 10/14/2011

Given the

number
primitive in JavaScript is an IEEE 754 64-bit floating point (known in other languages as a double), and using floats to model currencies is a bad idea, is a Money prototype (JavaScript) or a Coffeescript Class that eases use of pseudo-integer cents and string currency ISO 4217 code to represent currency available?

^ There's still gotta be a better way to say that.

I'm hoping to find something that mirrors the common design pattern of the many other languages out there that do include an integer primitive.

As examples, I'm familiar with the money gem for ruby, and the python-money package, both of which implement variations of this design pattern.

Ideally looking for something that will play nice with backbone.js and node.js, but all suggestions appreciated.

Edit 4: As far as I can tell, as long as an implementation of
roundDownOrUp ? floor : ceiling
is called on the Number after every operation (& in between chained operations) everything would function as if one were dealing with integers.




Old information, retained to document the history of the question.



I read How can I format numbers as money in JavaScript?
where I found accounting.js and jQuery Globalize which both do pretty printing but are not designed to model currencies and perform operations with them.

Edit 1: Just found JSorm Currency in the npm registry which is ISO 4217 aware, but does not appear to include any fixes for float "gotchas". Please correct if I have misread.

Edit 2 folded into rewrite.

Edit 3: It looks like a good option would be to use node-bigint as suggested by @RicardoTomasi.

Answer Source

Both bigdecimal.js and node-bigint have arbitrary precision.

I'd go with bigint. bigdecimal is a GWT version of of Java's BigDecimal, clocking in at 113kb, so the code is not what one would call readable.

update: money.js has just been released, but it uses javascript's native Number, and is focused on currency conversion.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download