views:

51

answers:

3

What can I use as a decimal type in JavaScript? It's not supported (0.1 + 0.2 !== 0.3), and I need it for representing exact values in a banking/financial application. See The State and Future of JavaScript for an good read and the dirty details behind JavaScript and its (lack of) support for decimal arithmetic.

By "decimal", I mean either:

  1. infinite-range and arbitrary-precision (like BigDecimal in Java), or
  2. limited range and precision, but suitable for financial calculations (like decimal in C#).

So, what library or solution exists for working with decimal values? Thanks!

+2  A: 

Javascript does have floating point support. But anyway, for financial records, the simplest implementation would simply be storing your values in standard integers. You may either declare an integer to represent the amount in cents, or two integers one for dollars and one for cents.

So $18.57 would become 1857cents in the first technique or 18 dollars and 57 cents in the second.

This has the added advantage of being completely accurate, as integers are stored purely as unique binary representation, there would be no such thing as rounding errors.

Razor Storm
Yeah, JavaScript has binary floating point, which is a bad choice for 99% of the applications that use JavaScript. Do any JavaScript libraries exist that abstract the concept of decimal for me?
Mr. X
Wouldn't it be simpler to just store it as integer like my example? All decimal implementations would have inherent inaccuracies due to how the architecture represents floating points. Don't worry about overflow, even the US national debt would fit neatly in a long type 64bit int.
Razor Storm
The integer part of JavaScript's floating point is less than 64 bits.
Mr. X
+2  A: 

It is often recommended1 to handle money as an integer representing the number of cents: 2572 cents instead of 25.72 dollars. This is to avoid the problems with floating-point arithmetic that you mention. Fortunately integer arithmetic in floating point is exact, so decimal representation errors can be avoided by scaling.


1Douglas Crockford: JavaScript: The Good Parts: Appendix A - Awful Parts (page 105).

Daniel Vassallo
How many bits are available in the integer part of JavaScript floating point? I might be able to squeeze it all in.
Mr. X
@Mr. X: almost certainly 53 or more.
ysth
@Mr. X: check out http://stackoverflow.com/questions/307179/what-is-javascripts-max-int-whats-the-highest-integer-value-a-number-can-go-to, and this: http://stackoverflow.com/questions/3428136/javascript-integer-math-incorrect-results
Daniel Vassallo
A: 

Take a look at BigNumber and that post too.

floatless
Just looking at that code makes me wanna cry. Interesting idea though, but it sucks to not be able to use regular operators `+ - / *` etc
Infinity