BigDecimal Class in Java - GeeksforGeeks

04 Dec, 2018
The BigDecimal class provides operations on double numbers for arithmetic, scale handling, rounding, comparison, format conversion and hashing. It can handle very large and very small floating point numbers with great precision but compensating with the time complexity a bit.A BigDecimal consists of a random precision integer unscaled value and a 32-bit integer scale. If greater than or equal to zero, the scale is the number of digits to the right of the decimal point. If less than zero, the unscaled value of the number is multiplied by 10^(-scale).
Examples:
Input : double a=0.03;
        double b=0.04;
        double c=b-a;
        System.out.println(c);
Output :0.009999999999999998

Input : BigDecimal _a = new BigDecimal("0.03");
        BigDecimal _b = new BigDecimal("0.04");
        BigDecimal _c = _b.subtract(_a);
        System.out.println(_c);
Output :0.01


Need Of BigDecimal
The two java primitive types(double and float) are floating point numbers, which is stored as a binary representation of a fraction and a exponent.
Other primitive types(except boolean) are fixed-point numbers. Unlike fixed point numbers, floating point numbers will most of the times return an answer with a small error (around 10^-19) This is the reason why we end up with 0.009999999999999998 as the result of 0.04-0.03 in the above example.
But BigDecimal provides us with the exact answer.
// Java Program to illustrate BigDecimal Class  import java.math.BigDecimal;public class BigDecimalExample{    public static void main(String[] args)     {        // Create two new BigDecimals        BigDecimal bd1 =                new BigDecimal("124567890.0987654321");        BigDecimal bd2 =                new BigDecimal("987654321.123456789");                  // Addition of two BigDecimals        bd1 = bd1.add(bd2);        System.out.println("BigDecimal1 = " + bd1);          // Multiplication of two BigDecimals        bd1 = bd1.multiply(bd2);        System.out.println("BigDecimal1 = " + bd1);          // Subtraction of two BigDecimals        bd1 = bd1.subtract(bd2);        System.out.println("BigDecimal1 = " + bd1);          // Division of two BigDecimals        bd1 = bd1.divide(bd2);        System.out.println("BigDecimal1 = " + bd1);          // BigDecima1 raised to the power of 2        bd1 = bd1.pow(2);        System.out.println("BigDecimal1 = " + bd1);          // Negate value of BigDecimal1        bd1 = bd1.negate();        System.out.println("BigDecimal1 = " + bd1);    }    }        
Output:-
BigDecimal1 = 1112222211.2222222211
BigDecimal1 = 1098491072963113850.7436076939614540479
BigDecimal1 = 1098491071975459529.6201509049614540479
BigDecimal1 = 1112222210.2222222211
BigDecimal1 = 1237038244911605079.77528397755061728521
BigDecimal1 = -1237038244911605079.77528397755061728521

Declaration
double a, b;                
BigDecimal A, B; 

Initialization:
a = 5.4;
b = 2.3;
A  = BigDecimal.valueOf(5.4);
B  = BigDecimal.valueOf(2.3); 

If you are given a String representation of a double number then you can initialize in the following manner:
A  = new BigDecimal(“5.4”);
B  = new BigDecimal(“1238126387123.1234”); 

For ease of initialization BigDecimal class has some pre-defined constants:
A = BigDecimal.ONE;
// Other than this, available constants
// are BigDecimal.ZERO and BigDecimal.TEN 

Mathematical operations:
int c = a + b;
BigDecimal C = A.add(B); 
Other similar function are subtract() , multiply(), divide(), pow()

But all these functions, except pow() which takes integer as its argument, take BigDecimal as their argument so if we want these operation with decimals or string convert them to BigDecimal before passing them to functions as shown below:
String str = “123456789.123456789”;
BigDecimal C = A.add(new BigBigDecimal(str));
double val  = 123456789.123456789;
BigDecimal C = A.add(BigDecimal.valueOf(val)); 

Extraction of value from BigDecimal:
// value should be in limit of double x
double x   =  A.doubleValue();   

// To get string representation of BigDecimal A
String z = A.toString();       

Comparison:
if (a < b) {}         // For primitive double
if (A.compareTo(B) < 0)  {} // For BigDecimal

Actually compareTo returns -1(less than), 0(Equal), 1(greater than) according to values.
For equality we can also use:
if (A.equals(B)) {}  // A is equal to B 

Methods of BigDecimal Class:
BigDecimal abs​(): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, and whose scale is this.scale().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.scale()).BigDecimal add​(BigDecimal augend, MathContext mc): This method returns a BigDecimal whose value is (this + augend), with rounding according to the context settings.byte byteValueExact​(): This method converts this BigDecimal to a byte, checking for lost information.int compareTo​(BigDecimal val): This method compares this BigDecimal with the specified BigDecimal.BigDecimal divide​(BigDecimal divisor): This method returns a BigDecimal whose value is (this / divisor), and whose preferred scale is (this.scale() – divisor.scale()); if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.BigDecimal divide​(BigDecimal divisor, int scale, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is as specified.BigDecimal divide​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this / divisor), with rounding according to the context settings.BigDecimal divide​(BigDecimal divisor, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is this.scale().BigDecimal[] divideAndRemainder​(BigDecimal divisor): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands.BigDecimal[] divideAndRemainder​(BigDecimal divisor, MathContext mc): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands calculated with rounding according to the context settings.BigDecimal divideToIntegralValue​(BigDecimal divisor): This method returns a BigDecimal whose value is the integer part of the quotient (this / divisor) rounded down.BigDecimal divideToIntegralValue​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is the integer part of (this / divisor).double doubleValue​(): This method converts this BigDecimal to a double.boolean equals​(Object x): This method compares this BigDecimal with the specified Object for equality.float floatValue​(): This method converts this BigDecimal to a float.int hashCode​(): This method returns the hash code for this BigDecimal.int intValue​(): This method converts this BigDecimal to an int.int intValueExact​(): This method converts this BigDecimal to an int, checking for lost information.long longValue​(): This method converts this BigDecimal to a long.long longValueExact​(): This method converts this BigDecimal to a long, checking for lost information.BigDecimal max​(BigDecimal val): This method returns the maximum of this BigDecimal and val.BigDecimal min​(BigDecimal val): This method returns the minimum of this BigDecimal and val.BigDecimal movePointLeft​(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the left.BigDecimal movePointRight​(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the right.BigDecimal multiply​(BigDecimal multiplicand): This method returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).BigDecimal multiply​(BigDecimal multiplicand, MathContext mc): This method returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings.BigDecimal negate​(): This method returns a BigDecimal whose value is (-this), and whose scale is this.scale().BigDecimal negate​(MathContext mc): This method returns a BigDecimal whose value is (-this), with rounding according to the context settings.BigDecimal plus​(): This method returns a BigDecimal whose value is (+this), and whose scale is this.scale().BigDecimal plus​(MathContext mc): This method returns a BigDecimal whose value is (+this), with rounding according to the context settings.BigDecimal pow​(int n): This method returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision.BigDecimal pow​(int n, MathContext mc): This method returns a BigDecimal whose value is (thisn).int precision​(): This method returns the precision of this BigDecimal.BigDecimal remainder​(BigDecimal divisor): This method returns a BigDecimal whose value is (this % divisor).BigDecimal remainder​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this % divisor), with rounding according to the context settings.BigDecimal round​(MathContext mc): This method returns a BigDecimal rounded according to the MathContext settings.int scale​(): This method returns the scale of this BigDecimal.BigDecimal scaleByPowerOfTen​(int n): This method returns a BigDecimal whose numerical value is equal to (this * 10n).BigDecimal setScale​(int newScale): This method returns a BigDecimal whose scale is the specified value, and whose value is numerically equal to this BigDecimal’s.BigDecimal setScale​(int newScale, RoundingMode roundingMode): This method returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value.short shortValueExact​(): This method converts this BigDecimal to a short, checking for lost information.int signum​(): This method returns the signum function of this BigDecimal.BigDecimal sqrt​(MathContext mc): This method returns an approximation to the square root of this with rounding according to the context settings.BigDecimal stripTrailingZeros​(): This method returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation.BigDecimal subtract​(BigDecimal subtrahend): This method returns a BigDecimal whose value is (this – subtrahend), and whose scale is max(this.scale(), subtrahend.scale()).BigDecimal subtract​(BigDecimal subtrahend, MathContext mc): This method returns a BigDecimal whose value is (this – subtrahend), with rounding according to the context settings.BigInteger toBigInteger​(): This method converts this BigDecimal to a BigInteger.BigInteger toBigIntegerExact​(): This method converts this BigDecimal to a BigInteger, checking for lost information.String toEngineeringString​(): This method returns a string representation of this BigDecimal, using engineering notation if an exponent is needed.String toPlainString​(): This method returns a string representation of this BigDecimal without an exponent field.String toString​(): This method returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.BigDecimal ulp​(): This method returns the size of an ulp, a unit in the last place, of this BigDecimal.BigInteger unscaledValue​(): This method returns a BigInteger whose value is the unscaled value of this BigDecimal.static BigDecimal valueOf​(double val): This method translates a double into a BigDecimal, using the double’s canonical string representation provided by the Double.toString(double) method.static BigDecimal valueOf​(long val): This method translates a long value into a BigDecimal with a scale of zero.static BigDecimal valueOf​(long unscaledVal, int scale): This method translates a long unscaled value and an int scale into a BigDecimal.
BigDecimal abs​(): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, and whose scale is this.scale().
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.scale()).
BigDecimal add​(BigDecimal augend, MathContext mc): This method returns a BigDecimal whose value is (this + augend), with rounding according to the context settings.
byte byteValueExact​(): This method converts this BigDecimal to a byte, checking for lost information.
int compareTo​(BigDecimal val): This method compares this BigDecimal with the specified BigDecimal.
BigDecimal divide​(BigDecimal divisor): This method returns a BigDecimal whose value is (this / divisor), and whose preferred scale is (this.scale() – divisor.scale()); if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.
BigDecimal divide​(BigDecimal divisor, int scale, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is as specified.
BigDecimal divide​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this / divisor), with rounding according to the context settings.
BigDecimal divide​(BigDecimal divisor, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is this.scale().
BigDecimal[] divideAndRemainder​(BigDecimal divisor): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands.
BigDecimal[] divideAndRemainder​(BigDecimal divisor, MathContext mc): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands calculated with rounding according to the context settings.
BigDecimal divideToIntegralValue​(BigDecimal divisor): This method returns a BigDecimal whose value is the integer part of the quotient (this / divisor) rounded down.
BigDecimal divideToIntegralValue​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is the integer part of (this / divisor).
double doubleValue​(): This method converts this BigDecimal to a double.
boolean equals​(Object x): This method compares this BigDecimal with the specified Object for equality.
float floatValue​(): This method converts this BigDecimal to a float.
int hashCode​(): This method returns the hash code for this BigDecimal.
int intValue​(): This method converts this BigDecimal to an int.
int intValueExact​(): This method converts this BigDecimal to an int, checking for lost information.
long longValue​(): This method converts this BigDecimal to a long.
long longValueExact​(): This method converts this BigDecimal to a long, checking for lost information.
BigDecimal max​(BigDecimal val): This method returns the maximum of this BigDecimal and val.
BigDecimal min​(BigDecimal val): This method returns the minimum of this BigDecimal and val.
BigDecimal movePointLeft​(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the left.
BigDecimal movePointRight​(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the right.
BigDecimal multiply​(BigDecimal multiplicand): This method returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).
BigDecimal multiply​(BigDecimal multiplicand, MathContext mc): This method returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings.
BigDecimal negate​(): This method returns a BigDecimal whose value is (-this), and whose scale is this.scale().
BigDecimal negate​(MathContext mc): This method returns a BigDecimal whose value is (-this), with rounding according to the context settings.
BigDecimal plus​(): This method returns a BigDecimal whose value is (+this), and whose scale is this.scale().
BigDecimal plus​(MathContext mc): This method returns a BigDecimal whose value is (+this), with rounding according to the context settings.
BigDecimal pow​(int n): This method returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision.
BigDecimal pow​(int n, MathContext mc): This method returns a BigDecimal whose value is (thisn).
int precision​(): This method returns the precision of this BigDecimal.
BigDecimal remainder​(BigDecimal divisor): This method returns a BigDecimal whose value is (this % divisor).
BigDecimal remainder​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this % divisor), with rounding according to the context settings.
BigDecimal round​(MathContext mc): This method returns a BigDecimal rounded according to the MathContext settings.
int scale​(): This method returns the scale of this BigDecimal.
BigDecimal scaleByPowerOfTen​(int n): This method returns a BigDecimal whose numerical value is equal to (this * 10n).
BigDecimal setScale​(int newScale): This method returns a BigDecimal whose scale is the specified value, and whose value is numerically equal to this BigDecimal’s.
BigDecimal setScale​(int newScale, RoundingMode roundingMode): This method returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value.
short shortValueExact​(): This method converts this BigDecimal to a short, checking for lost information.
int signum​(): This method returns the signum function of this BigDecimal.
BigDecimal sqrt​(MathContext mc): This method returns an approximation to the square root of this with rounding according to the context settings.
BigDecimal stripTrailingZeros​(): This method returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation.
BigDecimal subtract​(BigDecimal subtrahend): This method returns a BigDecimal whose value is (this – subtrahend), and whose scale is max(this.scale(), subtrahend.scale()).
BigDecimal subtract​(BigDecimal subtrahend, MathContext mc): This method returns a BigDecimal whose value is (this – subtrahend), with rounding according to the context settings.
BigInteger toBigInteger​(): This method converts this BigDecimal to a BigInteger.
BigInteger toBigIntegerExact​(): This method converts this BigDecimal to a BigInteger, checking for lost information.
String toEngineeringString​(): This method returns a string representation of this BigDecimal, using engineering notation if an exponent is needed.
String toPlainString​(): This method returns a string representation of this BigDecimal without an exponent field.
String toString​(): This method returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.
BigDecimal ulp​(): This method returns the size of an ulp, a unit in the last place, of this BigDecimal.
BigInteger unscaledValue​(): This method returns a BigInteger whose value is the unscaled value of this BigDecimal.
static BigDecimal valueOf​(double val): This method translates a double into a BigDecimal, using the double’s canonical string representation provided by the Double.toString(double) method.
static BigDecimal valueOf​(long val): This method translates a long value into a BigDecimal with a scale of zero.
static BigDecimal valueOf​(long unscaledVal, int scale): This method translates a long unscaled value and an int scale into a BigDecimal.
For more examples visit Java BigDecimal ExamplesRelated Articles:
Using BigDecimal in Java to calculate PI number up to 200 decimal digits
Make cents with BigDecimalFor more functions and details refer Class BigDecimalMy Personal Notes
arrow_drop_upSave
For more functions and details refer Class BigDecimal
Java-BigDecimal
Java-Data Types
Java-Functions
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Singleton Class in Java
Set in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
Initializing a List in Java
Overriding in Java
LinkedList in Java