29

I was reading BigDecimal Class but I was not able to find any information how BigDecimal class stores values in computer memory.

Do you know any reliable source that can provide this information?

Jan Ajan
  • 1,461
  • 3
  • 12
  • 15
  • 9
    Java is open source. I'd start just looking in its [source code](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/math/BigDecimal.java/). – BalusC May 18 '12 at 15:16
  • 5
    OK, but I'm not that good in Java to learn how it works from a source code. – Jan Ajan May 18 '12 at 15:17
  • 3
    Reading the source is one way to get better at Java. – trashgod May 18 '12 at 16:53
  • 12
    Unless you need an answer now and not in 10 weeks. – Jan Ajan May 18 '12 at 17:12
  • 3
    You're not going to get a _better_ answer than the answer from the source. In any event, the relevant part of the source code -- the class fields -- doesn't take very long at all to understand. – Louis Wasserman May 19 '12 at 00:13
  • 3
    Yes, the source provides the best answer. Provided you understand it. – Jan Ajan May 19 '12 at 06:46
  • 7
    To everybody telling OP to read the source code: I know it feels good to, um, act very knowledgeable around someone who is clearly a beginner, but reading the source code of a built-in class is pretty poor advice. Such classes are typically optimized for time and/or memory, and are not necessarily well-documented. A simple summary is much more valuable here. – Robert Dodier Nov 06 '20 at 02:10
  • Also, suggesting that someone UTSL in order to answer their own question implies that nobody should ever ask the question "how does this code work?" because, after all, they can just read it. In fact "how does this code work?" is a question we've all asked many times. – Willis Blackburn Nov 23 '21 at 17:16

2 Answers2

25

The unscaled value of the BigDecimal is stored in a BigInteger. The precision and scale are stored separately in integer fields:

BigInteger intVal
int scale
int precision

BigInteger stores the integer as a big-endian array of 32 bit integers, and the sign separately as another 32-bit integer.

int signum
int[] mag

But as Muhd says, if the number can fit in a 64 bit integer, then this is used instead of a BigInteger.

Greg Lowe
  • 15,430
  • 2
  • 30
  • 33
10

The significant digits of the number are stored in a long if the number of digits is sufficient to be fit in a long, otherwise they are stored in a BigInteger. In addition, BigDecimal has int primitives to represent the scale and precision, scale indicating the number of significant digits right of the decimal point, and precision indicating the number of significant digits total in the number.

Community
  • 1
  • 1
Muhd
  • 24,305
  • 22
  • 61
  • 78