Examples of Java BigDecimal Class
Arithmetic Operations
This Java code snippet creates two BigDecimal objects with decimal values of 12.5 and 3.0, respectively, performs arithmetic operations such as addition, subtraction, multiplication, and division on these objects, and prints the results after rounding to 2 decimal places.
Java
import java.math.BigDecimal;
public class BigDecimalExample {
public static void main(String[] args) {
BigDecimal ninja1 = new BigDecimal("9.45");
BigDecimal ninja2 = new BigDecimal("2.05");
// Addition
BigDecimal ninja_sum = ninja1.add(ninja2);
System.out.println("Sum of " + ninja1 + " and " + ninja2 + " is " + ninja_sum);
// Subtraction
BigDecimal ninja_diff = ninja1.subtract(ninja2);
System.out.println("Difference between " + ninja1 + " and " + ninja2 + " is " + ninja_diff);
// Multiplication
BigDecimal ninja_mul = ninja1.multiply(ninja2);
System.out.println("Product of " + ninja1 + " and " + ninja2 + " is " + ninja_mul);
// Division
BigDecimal ninja_div = ninja1.divide(ninja2, 2, BigDecimal.ROUND_HALF_UP);
System.out.println("Quotient of " + ninja1 + " and " + ninja2 + " is " + ninja_div);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Sum of 9.45 and 2.05 is 11.50
Difference between 9.45 and 2.05 is 7.40
Product of 9.45 and 2.05 is 19.3725
Quotient of 9.45 and 2.95 is 4.61
Achieving Precision
This code snippet creates a BigDecimal object in Java with the mathematical constant pi as its value. The scale of this object is then set to 3 decimal places using the HALF_UP rounding mode. Finally, the original value of the BigDecimal object and its rounded value are printed on the console.
Java
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalDemo {
public static void main(String[] args) {
BigDecimal ninja_value = new BigDecimal("3.14159265358979323846");
BigDecimal rounded_ninja = ninja_value.setScale(3, RoundingMode.HALF_UP);
System.out.println("Original ninja_value: " + ninja_value);
System.out.println("Rounded ninja_value: " + rounded_ninja);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Original ninja_value: 3.14159265358979323846
Rounded ninja_value: 3.142
Why use BigDecimal in Java?
- BigDecimal provides accurate and precise numerical calculations.
- BigDecimal provides flexibility in handling decimal numbers.
- BigDecimal can handle the smallest and largest floating point numbers accurately.
- BigDecimal provides platform-independent behavior across different platforms.
- BigDecimal also provides rounding modes, such as rounding up, rounding down, etc., that make the calculation more accurate.
- BigDecimals can not be changed. Hence these are immutable.
Declaration of BigDecimal in Java
You can declare BigDecimal in Java by creating a BigDecimal object like the following example:-
BigDecimal decimalValue = new BigDecimal("123.456789");
Syntax of BigDecimal class in Java
To perform operations on numbers, we need to begin creating a BigDecimal object.
The following constructors can be used:
- BigDecimal(double value): Creates a BigDecimal object by a double value.
- BigDecimal(String value): Creates a BigDecimal object by a String value.
- BigDecimal(BigInteger value): Creates a BigDecimal object by a BigInteger value.
After creating the BigDecimal objects, we can now perform arithmetic operations using the various methods provided by the class. Here’s an example code of adding two BigDecimal objects of data type double.
Java
import java.math.BigDecimal;
public class BigDecimalDemo {
public static void main(String[] args) {
// Two double values to be added
double ninja1 = 19.319, ninja2 = 9.54;
// Creating two objects from these given values
BigDecimal obj1 = BigDecimal.valueOf(ninja1);
BigDecimal obj2 = BigDecimal.valueOf(ninja2);
// adding these two objects by a method add
BigDecimal NinjaSum = obj1.add(obj2);
// printing all the values
System.out.println("ninja1 = " + ninja1);
System.out.println("ninja2 = " + ninja2);
System.out.println("NinjaSum of ninja1 and ninja2 is " + NinjaSum);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
ninja1 = 19.319
ninja2 = 9.54
NinjaSum of ninja1 and ninja2 is 28.859
We passed double values in BigDecimal objects and used the ‘add’ method provided by the BigDecimal class. Similarly, We can use more features provided by the BigDecimal class.
Methods of Java BigDecimal Class
Here are some important methods everyone should read:
- BigDecimal(String val): This constructor creates a new BigDecimal object from a passed string.
- add(BigDecimal val): This method returns a BigDecimal object by the addition of two BigDecimal objects.
- subtract(BigDecimal val): This method returns a BigDecimal object by subtraction in two BigDecimal objects.
- multiply(BigDecimal val): This method returns a BigDecimal object by multiplication of two BigDecimal objects.
- divide(BigDecimal divisor): This method returns a BigDecimal object by division of two BigDecimal objects.
- setScale(int scale, RoundingMode roundingMode): This method sets the scale of the BigDecimal object to the specified value scale and rounds the result using the specified rounding mode.
- compareTo(BigDecimal val): This method compares the BigDecimal object with the BigDecimal val.
- equals(Object obj): This method compares the BigDecimal object with the specified object for equality.
- doubleValue(): This method converts the BigDecimal object to a double value.
- toString(): This method type-casts to string data type value.
- intValue(): This method converts a BigDecimal object to an int value.
- longValue(): This method converts a BigDecimal object to a long value.
- negate(): This method returns a BigDecimal object whose value is the negation of a BigDecimal object.
- abs(): This method returns a BigDecimal object whose value is the absolute value of a BigDecimal object.
- stripTrailingZeros(): This method returns a BigDecimal object with all trailing zeros removed from a fractional part of the value.
- boolean equals(Object x): This method checks if the current BigDecimal object is equal to the specified object x. It returns true if they are equal in both value and precision, otherwise returns false.
- float floatValue(): Returns the float value equivalent to the current BigDecimal object. This conversion may involve rounding or truncation.
- int hashCode(): Computes a hash code for the BigDecimal object. It's typically used when storing objects in hash-based collections like HashMap.
- int intValue(): Returns the integer value of the current BigDecimal object after truncating any decimal digits. If the number cannot be represented as an integer without losing information, an ArithmeticException is thrown.
- int intValueExact(): Returns the integer value of the current BigDecimal object if it can be represented as an integer without losing any precision. Otherwise, it throws an ArithmeticException.
- long longValue(): Returns the long value of the current BigDecimal object after truncating any decimal digits. Similar to intValue(), but for long type.
- long longValueExact(): Returns the long value of the current BigDecimal object if it can be represented as a long without losing any precision. Otherwise, it throws an ArithmeticException.
- BigDecimal max(BigDecimal val): Returns the larger of the current BigDecimal object and the specified val.
- BigDecimal min(BigDecimal val): Returns the smaller of the current BigDecimal object and the specified val.
- BigDecimal movePointLeft(int n): Moves the decimal point of the current BigDecimal object to the left by n positions. If n is positive, it moves the decimal point to the left; if n is negative, it moves it to the right.
- BigDecimal movePointRight(int n): Moves the decimal point of the current BigDecimal object to the right by n positions.
- BigDecimal pow(int n): Raises the current BigDecimal object to the power of n.
- BigDecimal remainder(BigDecimal divisor): Returns the remainder of dividing the current BigDecimal object by the specified divisor.
- BigDecimal round(MathContext mc): Returns a BigDecimal object whose value is rounded according to the rules specified in the given MathContext.
- BigDecimal scale(): Returns the scale of the current BigDecimal object.
- BigDecimal signum(): Returns the signum function of the BigDecimal object (1 for positive, 0 for zero, -1 for negative).
- BigDecimal setScale(int newScale): Sets the scale of the current BigDecimal object to a new value without specifying rounding.
- BigDecimal setScale(int newScale, RoundingMode roundingMode): Sets the scale of the BigDecimal object to a new value and specifies how to round.
- BigDecimal stripTrailingZeros(): Returns a BigDecimal object with trailing zeros removed.
- BigDecimal toEngineeringString(): Converts the BigDecimal object to its engineering string representation.
- BigDecimal toPlainString(): Returns a string representation of the BigDecimal without scientific notation.
- BigDecimal toBigInteger(): Converts the BigDecimal to a BigInteger.
- BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode): Divides the current BigDecimal by the specified divisor, specifying the scale and rounding mode.
- BigDecimal multiply(BigDecimal multiplicand, MathContext mc): Multiplies the current BigDecimal by another BigDecimal, specifying the MathContext for precision.
- BigDecimal subtract(BigDecimal subtrahend, MathContext mc): Subtracts the specified BigDecimal from the current one, using the specified MathContext.
- BigDecimal add(BigDecimal augend, MathContext mc): Adds the specified BigDecimal to the current one, using the specified MathContext.
- BigDecimal fromBigInteger(BigInteger bigInteger): Creates a BigDecimal from a BigInteger.
- BigDecimal fromBigInteger(BigInteger bigInteger, MathContext mc): Creates a BigDecimal from a BigInteger, using the specified MathContext.
- BigDecimal valueOf(double val): Returns a BigDecimal that represents the specified double value.
- BigDecimal valueOf(long val): Returns a BigDecimal that represents the specified long value.
- BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode): Divides the current BigDecimal by the specified divisor and applies the rounding mode.
- BigDecimal divideAndRemainder(BigDecimal divisor): Divides the current BigDecimal by the specified divisor and returns both the quotient and the remainder.
- BigDecimal negate(MathContext mc): Negates the current BigDecimal with a specified MathContext.
- BigDecimal scaleByPowerOfTen(int n): Returns a BigDecimal whose value is equal to the current value scaled by 10 raised to the power of n.
- BigDecimal round(MathContext mc): Rounds the current BigDecimal to the specified MathContext settings.
Advantages of BigDecimal Class in Java
- High-Level of precision can be achieved by using BigDecimal for decimal arithmetic operations
- BigDecimal provides various operations such as addition, subtraction, multiplication, division, etc.
- For better accuracy, BigDecimal allows setting the scale to a specific value.
Disadvantages of BigDecimal Class in Java
- Primitive data types such as float and double are more efficient than BigDecimal objects because BigDecimal objects take more memory than the primitive data type values.
- Not all beginners are familiar with BigDecimal, so the code can be difficult to understand for beginners.
- BigDecimal gives you an accurate solution, but operations are slower and take more time to compute.
Also check out Addition of Two Numbers in Java here.
Frequently Asked Questions
What is the size of a BigDecimal?
The size of a BigDecimal object in bytes depends on its internal representation, which can vary based on the number's precision.
What operations does Java BigDecimal provide?
The BigDecimal class offers a range of functionalities, including arithmetic operations, scale manipulation, rounding, comparison, hashing, and format conversion.
How Java BigDecimal is different from double?
Double is a primitive data type that is used to store floating-point numbers but with limited precision. On the other hand, BigDecimal provides a higher precision on floating-point numbers. We need to create an object of BigDecimal in order to store a value and do operations on it. whereas In double, we only need to create a variable.
How a Java BigDecimal object can be converted to a primitive data type?
Java BigDecimal provides some methods to convert the BigDecimal objects to a primitive data type, such as intValue(), floatValue(), and doubleValue(). Here is a syntax on how to use these methods, ‘float val = obj.floatValue()’. This syntax will convert the BigDecimal Object (obj) to a float value primitive data type.BigDecimal(String val): Creates a new BigDecimal object from a passed string.
Is Java BigDecimal immutable?
Yes, Java's `BigDecimal` is immutable, meaning that once a `BigDecimal` object is created, its value cannot be changed. Any arithmetic operation on a `BigDecimal` returns a new instance instead of modifying the original object.
Conclusion
The BigDecimal class in Java provides a powerful tool for performing arithmetic operations on decimal numbers with high precision and control over rounding. We discussed what Java BigDecimal is, why we should use it, and the syntax with an example of Java BigDecimal. We also discussed the pros and cons of Bigdecimal and some important methods of BigDecimal. At last, discussed two examples of BigDecimal where we used BigDecimal Objects and Methods in Java Code.
I will recommend you to take a read at more features of Java version 8 here and also read about the standalone applications in Java here; this will surely boost your journey of Java.