I am considering writing two limited precision alternatives to BigDecimal, namely DecimalInt and DecimalLong. These would be capable of dealing with numbers within the real bounds of int and long with an arbitrary number of decimal places, creatable in both mutable and immutable form. My plan is to make DecimalInt support +/-999,999,999 to +/- 0.999999999 and DecimalLong the same, but with up to 18 digits.
This would be done by maintaining a decimal digit count value of 0-9 for DecimalInt and 0-18 for DecimalLong along side the actual value stored as a scaled int or long. The normal use would be for small numbers of decimals such as for money and stock prices, typically 2-4 decimal places.
The essential requirements are (a) lean footprint (2 classes, plus OverflowException), and (b) full support of all basic operations plus all of Math that makes sense.
Googling for results did not return any obvious hits - they all seemed to pertain to arbitrary decimals.
My questions are: Has this already been done? Are there hidden subtleties in this which is why it has not already been done? Has anyone heard rumors of Java supporting a decimal type like DotNet's.
EDIT: This is different from BigDecimal because it should be (a) a hell of a lot more efficient to not deal with an array of ints, and (b) it won't wrap BigInteger so it will be leaner on memory too, and (c) it will have a mutable option so it will be faster there as well. In summary - less overhead for the simple use cases like "I want to store a bank balance without the overhead of BigDecimal and the inaccuracy of double".
EDIT: I intend on doing all the math using int or long to avoid the classic problem of: 1586.60-708.75=877.8499999999999 instead of 877.85
I strongly suspect the reason why this has not been done is that the overhead of BigDecimal and BigInteger is not as relevant as you think, and avoiding it not worth the effort and the risk of getting it wrong in some subtle way.
To use your example: for any financial application, saving a few dozen bytes is a non-issue and limited precision a deal-breaker (stock prices my have typically 2-4 digits in the USA, but if you want to deal with emerging markets, you'll encounter currencies with runaway inflation, where a 15-digit sum buys you half a loaf of bread).
Basically, it sounds like just another case of premature optimization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With