Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get biggest BigDecimal value

How can I get the largest possible value of a BigDecimal variable can hold? (Preferably programmatically, but hardcoding would be ok too)

EDIT
OK, just realized there is no such thing since BigDecimal is arbitrary precision. So I ended up with this, which is sufficiently big for my purpose:
BigDecimal my = BigDecimal.valueOf(Double.MAX_VALUE)

like image 699
Caner Avatar asked Jul 22 '11 15:07

Caner


People also ask

What is BigDecimal max value?

max(BigDecimal val) method in Java is used to compare two BigDecimal values and return the maximum of the two. This is opposite to BigDecimal max() method in Java.

How do I get scale for BigDecimal?

If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by the BigDecimal is therefore (unscaledValue × 10-scale).

How do I know if BigDecimal is bigger than other BigDecimal?

compareTo(BigDecimal bg) method checks for equality of this BigDecimal and BigDecimal object bg passed as parameter. The method considers two equal BigDecimal objects even if they are equal in value irrespective of the scale.

How do I use BigDecimal valueOf?

valueOf(double val) is an inbuilt method in java that translates a double into a BigDecimal, using the double's canonical string representation provided by the Double. toString(double) method.


2 Answers

Its an arbitrary precision class, it will get as large as you'd like until your computer runs out of memory.

like image 108
alexblum Avatar answered Sep 23 '22 08:09

alexblum


Looking at the source BigDecimal stores it as a BigInteger with a radix,

private BigInteger intVal; private int scale; 

and from BigInteger

/** All integers are stored in 2's-complement form. 63:    * If words == null, the ival is the value of this BigInteger. 64:    * Otherwise, the first ival elements of words make the value 65:    * of this BigInteger, stored in little-endian order, 2's-complement form. */ 66:   private transient int ival; 67:   private transient int[] words; 

So the Largest BigDecimal would be,

ival = Integer.MAX_VALUE; words = new int[Integer.MAX_VALUE];  scale = 0; 

You can figure out how to set that. :P

[Edit] So just to calculate that, In binary that's,

(2^35)-2 1's (I think?)

in 2's complement

01111111111111111...until your RAM fills up.

like image 22
Andrew Avatar answered Sep 25 '22 08:09

Andrew