How to get biggest BigDecimal value

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

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 good for my purpose:
BigDecimal my = BigDecimal.valueOf(Double.MAX_VALUE)

回答1:

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



回答2:

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.



回答3:

Given enough RAM, the value is approximately:

2240*10232

(It's definitely out by a few orders of magnitude but in relative terms it's a very precise estimate.)



回答4:

You can represent 2^2147483647-1 however after this value some methods do not work as expected. It has 646456993 digits.

System.out.println(BigInteger.ONE.shiftLeft(Integer.MAX_VALUE)                                  .subtract(BigInteger.ONE).bitLength()); 

prints

2147483647 

however

System.out.println(BigInteger.ONE.shiftLeft(Integer.MAX_VALUE).bitLength()); 

prints

-2147483648 

as there is an overflow in the number of bits.

BigDecimal.MAX_VALUE is large enough that you shouldn't need to check for it.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!