Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How BigDecimal is implemented?

Tags:

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?

like image 358
Jan Ajan Avatar asked May 18 '12 15:05

Jan Ajan


People also ask

How does Big decimal work?

A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. 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.

How do you make BigDecimal?

BigDecimal abs​(MathContext mc): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, with rounding according to the context settings. BigDecimal add​(BigDecimal augend): This method returns a BigDecimal whose value is (this + augend), and whose scale is max(this. scale(), augend.

Why do we use BigDecimal in Java?

BigDecimal is Oracle's arbitrary-precision numerical library. BigDecimal is part of the Java language and is useful for a variety of applications ranging from the financial to the scientific (that's where sort of am).

Why use BigDecimal instead of double in Java?

The BigDecimal(String) constructor should always be preferred over BigDecimal(Double) because using BigDecimal(double) is unpredictable due to the inability of the double to represent 0.1 as exact 0.1.


2 Answers

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.

like image 88
Greg Lowe Avatar answered Dec 06 '22 17:12

Greg Lowe


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.

like image 44
Muhd Avatar answered Dec 06 '22 17:12

Muhd