5

I'm looking to have a java class that will hold a decimal value with an arbitrary pre-set precision. The class BigDecimal looks to be a good candidate as a starting point, but I want to able to limit the size of the decimal to whatever an end user decides. Literally speaking, the end user would specify a range in base 10 and I would allocate enough bytes to represent any number in that range.

I was thinking of having a class that extends BigDecimal. In this class I would add the functions necessary to mimic a decimal within a pre-set range.

My questions to the community are: Are there any libraries that already do this?
Would extending BigDecimal be a reasonable thing to do?

Carlos Bribiescas
  • 4,197
  • 9
  • 35
  • 66
  • Specify a range? maximum value? maximum absolute value? number of decimal digits? number of decimal places? NB the 'are there any libraries' part of this question is off-topic. – user207421 Apr 09 '14 at 04:13
  • 1
    Note that BigDecimal already has a scale value which, when positive, essentially limits the number of digits to the right of the decimal point. You can also supply [MathContext](http://docs.oracle.com/javase/7/docs/api/java/math/MathContext.html) to maintain this scale. – Gassa Apr 09 '14 at 04:14
  • So, what difference do you need from the existing behavior? If it is performance, as the tags suggest, what order is the expected length of the decimals - tens? thousands? And more importantly, have you benchmarked BigDecimal in your use case and confirmed that the bottleneck is exactly in how they deal with scale? – Gassa Apr 09 '14 at 04:14
  • I need Performance and a fixed byte size in advanced. The length of decimals can be any order of magnitude. It maybe be small if you just want accurate money representation. This class will represent an option for an end user who wishes to sacrifice performance for accuracy on a case by case basis. The fixed, arbitrary, byte size is critical though, more than performance. – Carlos Bribiescas Apr 09 '14 at 13:58

2 Answers2

2

I would suggest you an intermediate way in between the proposals you made:

The Apfloat library is a good way to try with, check out the API docs.
Apcomplex is a wrapper class for e.g. a BigDecimal.

So here you would have a big freedom on overriding and enhancing new methods just applying this class.

GingerHead
  • 8,130
  • 15
  • 59
  • 93
1

Interestingly BigDecimal has everything you need already. The simple methods add(BigDecimal), multiply(BigDecimal), etc.. work with unlimited precision.

The methods add(BigDecimal,MathContext), multiply(BigDecimal,MathContext), etc.. allow specifying a requested upperbound on the number of digits the resulting mantissa should have.

So basically you get results back in the form:

sign * mantissa * 10^exponent

With the guarantee that 0=< mantissa < 10^requested. The methods do a rounding according to the mode specified in the MathContext.