Java BigDecimal class is used when developer is working around financial data. The Java BigDecimal class provides several operations on double numbers. Java BigDecimal class is preferred when arithmetics with high-precision are used or whenever there is a need of multiple round-off calculations.
BigDecimal class is an Immutable class. Java BigDecimal class is defined in java.math package.
Java BigDecimal class hierarchy
public class BigDecimal extends Number implements Comparable<BigDecimal>
Various Operations provided by Java BigDecimal class includes
- Rounding-off arithmetics.
- Scale handling.
- Comparison based calculations.
- Format conversion of numbers and hashing.
Java BigDecimal class handles very small to very large floating point numbers but time complexity should not be ignored by developer.
Java BigDecimal represents an immutable arbitrary-precision arithmetic decimal number.
Java BigDecimal consists of two parts
- Unscaled value : an arbitrary precision integer
- Scale : a 32-bit integer which represents the number of digits to the right of the decimal point
- For example, the BigDecimal 5.16 has the unscaled value of 516 and the scale of 2.
- If number is greater than or equal to zero, the scale is the number of digits to the right of the decimal point.
- If number is less than zero, the unscaled value of the number is multiplied by 10^(-scale).
Example :Input : double x=0.03; double y=0.04; double z=y-x; System.out.println(z); Output :0.009999999999999998 Input : BigDecimal _x = new BigDecimal("0.03"); BigDecimal _y = new BigDecimal("0.04"); BigDecimal _z = _y.subtract(_x); System.out.println(_z); Output :0.01
Java BigDecimal Declaration
double x, y; BigDecimal X, Y;
Java BigDecimal Initialization
x = 8.9; y = 4.3; X = BigDecimal.valueOf(8.9); Y = BigDecimal.valueOf(4.3);
String representation of a double number
X = new BigDecimal(“7.3”); Y = new BigDecimal(“14536789844.2314”);
BigDecimal initialization using predefined constants
X = BigDecimal.ONE; Y = BigDecimal.ZERO; Z = BigDecimal.TEN;
Mathematical operations on Java BigDecimal
int Z = X + Y; BigDecimal Z = X.add(Y); BigDecimal Z = X.subtract(Y); BigDecimal Z = X.multiply(Y); BigDecimal Z = X.divide(Y); //Please note, all above methods accept BigDecimal as parameters.
Access values from Java BigDecimal
// note that value should be in limit of double X double Y = X.doubleValue(); // below method is used to get string representation of BigDecimal X String Z = X.toString();
Comparisons of Java BigDecimals
if (A.compareTo(B) < 0) {} // compareTo returns -1(if A is less than B), 0(if A is Equal to B), 1(A is greater than B). if (A.equals(B)) {} // A is equal to B //returns true is A is equal to B
Java BigDecimal constructors
Constructor |
Description |
BigDecimal(BigInteger val) | It takes BigInteger as parameter and creates a BigDecimal Object of it. |
BigDecimal(BigInteger unscaledVal, int scale) | It takes BigInteger as parameter and creates a BigDecimal Object , additionally we can provide scale for the BigDecimal. |
BigDecimal(BigInteger val, MathContext mc) | It also creates object as per above constructors but additionally we can provide instance of MathContext while creating the object.
Basically, it provides precision matching IEEE 754R Format. Below are the possible values for java.math.MathContext: MathContext.DECIMAL128 ? : provides precision of 34 digits. |
BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) | Finally, In this constructor we can provide both scale and MathContext instance. |
Java BigDecimal methods
Methods | Description |
BigDecimal abs() | It returns a BigDecimal whose value is absolute value of invoking BigDecimal, and whose scale is this.scale(). |
BigDecimal abs(MathContext mc) | It returns a BigDecimal whose value is absolute value of invoking BigDecimal,with rounding accoriding to MathContext. |
BigDecimal add(BigDecimal aug) | It returns a BigDecimal with value as (this + aug), and scale as max(this.scale(), aug.scale()). |
BigDecimal add(BigDecimal augend, MathContext mc) | It returns a BigDecimal with value as (this + aug), with rounding accoriding to MathContext. |
byte byteValueExact(): | It converts this BigDecimal to a byte. It is used for checking the lost information. |
int compareTo(BigDecimal val) | It compares this / invoking BigDecimal with the specified BigDecimal. |
BigDecimal divide(BigDecimal divisor) | It returns a BigDecimal whose value is (this / divisor), and preferred scale is (this.scale() – divisor.scale()). In case, the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown by the method. |
BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) | It returns a BigDecimal whose value is (this / divisor) and scale is as provided in parameter : scale. |
BigDecimal divide(BigDecimal divisor, MathContext mc) | It returns a BigDecimal whose value is (this / divisor), and its rounding is according to the context provided. |
BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) | It returns a BigDecimal whose value is (this / divisor) and scale is this.scale(). |
BigDecimal[] divideAndRemainder(BigDecimal divisor) | It returns a two-element array of BigDecimal which contains the result of divideToIntegralValue followed by the result of remainder on the two operands. |
BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) | Itreturns a two-element array of BigDecimal which contains the result of divideToIntegralValue followed by the result of remainder on the two operands calculated with rounding according to the MathContext provided. |
BigDecimal divideToIntegralValue(BigDecimal divisor) | It returns a BigDecimal whose value is the integer part of the quotient (this / divisor) rounded down. |
BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) | It returns a BigDecimal whose value is the integer part of (this / divisor). |
double doubleValue() | It converts this BigDecimal to a double. |
boolean equals(Object x): | It compares this BigDecimal with the specified Object for equality. |
float floatValue(): | It converts this BigDecimal to a float. |
int hashCode(): | It returns the hash code for this BigDecimal. |
int intValue(): | It converts this BigDecimal to an int. |
int intValueExact(): | It converts this BigDecimal to an int ; checking for lost information. |
long longValue(): | It converts this BigDecimal to a long. |
long longValueExact(): | It converts this BigDecimal to a long ; checking for lost information. |
BigDecimal max(BigDecimal val): | It returns the maximum of this BigDecimal and val. |
BigDecimal min(BigDecimal val): | It returns the minimum of this BigDecimal and val. |
BigDecimal movePointLeft(int n): | It returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the left. |
BigDecimal movePointRight(int n): | It returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the right. |
BigDecimal multiply(BigDecimal multiplicand): | It returns a BigDecimal whose value is (this x multiplicand), and scale is (this.scale() + multiplicand.scale()). |
BigDecimal multiply(BigDecimal multiplicand, MathContext mc): | It returns a BigDecimal whose value is (this x multiplicand), with rounding according to the context provided. |
BigDecimal negate(): | It returns a BigDecimal whose value is (-this), and whose scale is this.scale(). |
BigDecimal negate(MathContext mc): | It returns a BigDecimal whose value is (-this), with rounding according to the context provided. |
BigDecimal plus(): | It returns a BigDecimal whose value is (+this), and whose scale is this.scale(). |
BigDecimal plus(MathContext mc): | It returns a BigDecimal whose value is (+this), with rounding according to the context provided. |
BigDecimal pow(int n): | It returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision. |
BigDecimal pow(int n, MathContext mc): | It returns a BigDecimal whose value is (thisn). |
int precision(): | It returns the precision of the invoking BigDecimal. |
BigDecimal remainder(BigDecimal divisor): | It returns a BigDecimal whose value is (this % divisor). |
BigDecimal remainder(BigDecimal divisor, MathContext mc): | It returns a BigDecimal whose value is (this % divisor), with rounding according to the context provided, |
BigDecimal round(MathContext mc): | It returns a BigDecimal rounded according to the MathContext settings. |
int scale(): | It returns the scale of this BigDecimal. |
BigDecimal scaleByPowerOfTen(int n): | It returns a BigDecimal whose numerical value is equal to (this * 10n). |
BigDecimal setScale(int newScale): | It 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): | It 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(): | It converts this BigDecimal to a short, checking for lost information. |
int signum(): | It returns the signum function of this BigDecimal. |
BigDecimal sqrt(MathContext mc): | It returns an approximation to the square root of this with rounding according to the context provided |
BigDecimal stripTrailingZeros(): | It returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. |
BigDecimal subtract(BigDecimal subtrahend): | It returns a BigDecimal whose value is (this – subtrahend), and whose scale is max(this.scale(), subtrahend.scale()). |
BigDecimal subtract(BigDecimal subtrahend, MathContext mc) | It returns a BigDecimal whose value is (this – subtrahend), with rounding according to the context provided. |
BigInteger toBigInteger() | It converts this BigDecimal to a BigInteger. |
BigInteger toBigIntegerExact(): | It converts this BigDecimal to a BigInteger, checking for lost information. |
String toEngineeringString() | It returns a string representation of this BigDecimal, using engineering notation if an exponent is needed. |
String toPlainString() | It returns a string representation of this BigDecimal without an exponent field. |
String toString() | It returns the string representation of this BigDecimal, using scientific notation if an exponent is needed. |
BigDecimal ulp(): | It returns the size of an ulp, a unit in the last place, of this BigDecimal. |
BigInteger unscaledValue(): | It returns a BigInteger whose value is the unscaled value of this BigDecimal. |
static BigDecimal valueOf(double val) | It 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): | It translates a long value into a BigDecimal with a scale of zero. |
static BigDecimal valueOf(long unscaledVal, int scale) | It translates a long unscaled value and an int scale into a BigDecimal. |
Java BigDecimal Examples
// Program to illustrate Java BigDecimal Class import java.math.BigDecimal; public class BigDecimalEx { public static void main(String[] ar) { // Code to create two new BigDecimals BigDecimal ob1 = new BigDecimal("153748363.057358253"); BigDecimal ob2 = new BigDecimal("95826836383.17352883"); // Code for addition of two BigDecimals ob1 = ob1.add(ob2); System.out.println("BigDecimal = " + ob1); // Code for multiplication of two BigDecimals ob1 = ob1.multiply(ob2); System.out.println("BigDecimal = " + ob1); // Code for subtraction of two BigDecimals ob1 = ob1.subtract(ob2); System.out.println("BigDecimal = " + ob1); // Code for ivision of two BigDecimals ob1 = ob1.divide(ob2); System.out.println("BigDecimal = " + ob1); // BigDecima1 raised to the power of 2 ob1 = ob1.pow(2); System.out.println("BigDecimal = " + ob1); // Negate value of BigDecimal1 ob1 = ob1.negate(); System.out.println("BigDecimal = " + ob1); } }Output :
BigDecimal = 95980584746.230887083 BigDecimal = 9197515790438388191017.31843353437510289 BigDecimal = 9197515790342561354634.14490470437510289 BigDecimal = 95980584745.230887083 BigDecimal = 9212272648036448069497.868006515096248889 BigDecimal = -9212272648036448069497.868006515096248889
Java BigDecimal Example for comparing two BigDecimals
In this example, we will demonstrate the use of compareTo method of Java BigDecimal :
//Java program illustrating compareTo method of BigDecimal import java.math.*; public class BigDecimalExample { public static void main(String[] args) { // code to create 2 BigDecimal instances BigDecimal bd1 = new BigDecimal("50.02"); BigDecimal bd2 = new BigDecimal("30.65"); //code for comparing b1 and b2 int output = bd1.compareTo(bd2); if( output == -1 ) System.out.println("First BigDecimal is lesser than the Second BigDecimal"); else if( output == 1 ) System.out.println("First BigDecimal is greater than the Second BigDecimal"); else if( output == 0) System.out.println("First BigDecimal is equal to the Second BigDecimal"); } }Output :
First BigDecimal is greater than the Second BigDecimal
Java BigDecimal Example for scaling BigDecimals
In this example, we will demonstrate the use of setScale method of Java BigDecimal :
//Java program illustrating setScale method of BigDecimal import java.math.*; public class BigDecimalExample { public static void main(String[] args) { BigDecimal bd = new BigDecimal("23.26435172"); bd=bd.setScale(4, BigDecimal.ROUND_HALF_UP); System.out.println("BigDecimal Rounding to 4 decimal place is: "+bd); } }Output:
BigDecimal Rounding to 4 decimal place is: 23.2644
Java BigDecimal Example for converting String to BigDecimals
In this example, we will demonstrate how to convert the String to BigDecimal in Java :
//Java program demonstrating how to convert String to BigDecimal in Java import java.math.*; public class BigDecimalExample { public static void main(String[] args) { String data="34.45"; BigDecimal bd=new BigDecimal(data); System.out.println("Converted String to bigDecimal: "+bd); } }Output :
Converted String to bigDecimal: 34.45
Java BigDecimal Example for converting BigDecimal to String
In this example, we will demonstrate how to convert the BigDecimal to String in Java using toString method of Java BigDecimal:
//Java program demonstrating use of toString method of BigDecimal in Java import java.math.*; public class BigDecimalExample { public static void main(String[] args) { BigDecimal bd=new BigDecimal("34.18"); String bdToString=bd.toString(); System.out.println(bdToString); } }Output :
34.18
Java BigDecimal Example for addition of two BigDecimals
In this example, we will demonstrate how to add two bigDecimal in Java using add method of Java BigDecimal:
//Java program demonstrating addition of two BigDecimal using add method of BigDecimal import java.math.*; public class BigDecimalExample { public static void main(String args[]) { BigDecimal bd1=new BigDecimal("12.2"); BigDecimal bd2=new BigDecimal("13.5"); BigDecimal result=bd1.add(bd2); System.out.println(result.toString()); } }Output :
25.7
Java BigDecimal Example for subtraction of two BigDecimals
In this example, we will demonstrate how to subtract two bigDecimal in Java using subtract method of Java BigDecimal:
//Java program demonstrating subtraction of two BigDecimal using subtract method of BigDecimal import java.math.*; public class BigDecimalExample { public static void main(String args[]) { BigDecimal bd1=new BigDecimal("12.4"); BigDecimal bd2=new BigDecimal("3.5"); BigDecimal result=bd1.subtract(bd2); System.out.println(result.toString()); } }
Output :
8.9
Java BigDecimal Example for multiplication of two BigDecimals
In this example, we will demonstrate how to multiply two bigDecimal in Java using multiply method of Java BigDecimal:
//Java program demonstrating multiplication of two BigDecimal using multply method of BigDecimal import java.math.*; public class BigDecimalExample { public static void main(String args[]) { BigDecimal bd1=new BigDecimal("14.4"); BigDecimal bd2=new BigDecimal("3.5"); BigDecimal result=bd1.multiply(bd2); System.out.println(result.toString()); } }Output:
50.40
Java BigDecimal Example for division of two BigDecimals
In this example, we will demonstrate how to divide two bigDecimal in Java using divide method of Java BigDecimal:
//Java program demonstrating division of two BigDecimal using divide method of BigDecimal import java.math.*; public class BigDecimalExample { public static void main(String args[]) { BigDecimal bd1=new BigDecimal("18.2"); BigDecimal bd2=new BigDecimal("5.2"); BigDecimal result=bd1.divide(bd2); System.out.println(result.toString()); } }Output :
3.5
Java BigDecimal Example for removing trailing zero from BigDecimal
In this example, we will demonstrate how to remove trailing zero from bigDecimal in Java using stripTrailingZeros method of BigDecimal and the use of toPlainString method :
//Java program demonstrating division of two BigDecimal using divide method of BigDecimal import java.math.*; public class BigDecimalExample { public static void main(String args[]) { BigDecimal bd1=new BigDecimal("30.400"); System.out.println(bd1.stripTrailingZeros().toPlainString()); } }Output :
30.4
Interview questions and answers for BigDecimal in Java
A) What is the difference between scale and round method of BigDecimal ?
Round method of BigDecimal class would round it to integer places irrespective of if it’s decimal places or not whereas Scale would only round it to the decimal places.
B) Have you ever encountered problems working with rounding decimal places arithmetics and what were the reasons ?
This is a tricky question and interviewer would judge your analytical skills with this question. Here is the perfect answer for this question :
I have faced multiple problems when working with rounding decimal places and these were :
1. Some operations on double numbers does not return the exact fractions e.g. the problem with double (a*100)/100 wouldn’t return exact a but will return few fractions lesser than a and when you are using floor rounding , it makes a big difference and creates huge problem in data.
2. Rounding the number only after getting a result vs rounding each outcome of 2 operand makes a huge difference.
3. Usage of inappropriate Rounding mode and Rounding scale always creates problem.
4. Results with double and BigDecimal are very different.
C) Which of the following data type you will prefer to store price – BigDecimal or Double ?
When working with financial data , BigDecimal is always recommended but considering that memory and Performance is not a critical concern, otherwise use double.
D) What is the difference between BigDecimal vs Double?
Double | BigDecimal |
Double is a wrapper class for the Java native double type, a 64-bit floating point number. | BigDecimal is an arbitrary-precision arithmetic. BigDecimal can represent numbers to many bits of precision. Technically, BIgDecimal is limited to a 32 bit exponent, but that is definitely enough for anybody. |
Implementation : Double will compile down to native CPU operations, it is light-weight. | Implementation : BigDecimal will be far more heavyweight. |
Double has a certain precision. | BigDecimal is an exact way of representing numbers, especially financial data. |
Result may vary. | Provides accurate result. |
For more interview questions and answers for Java : Go here .
Thanks a lot for reading this article.
Please share your queries / suggestions / questions in below comment box. You can also directly connect with me through social media accounts.