1.
Introduction
2.
What is Java BigDecimal?
3.
Examples of Java BigDecimal
3.1.
Arithmetic Operations
3.2.
Java
3.3.
Achieving Precision
3.4.
Java
4.
Why use Java BigDecimal
5.
Declaration of BigDecimal in Java
6.
Syntax of Java BigDecimal
6.1.
Java
7.
Methods of Java BigDecimal
8.
Pros of BigDecimal in Java
9.
Cons of BigDecimal in Java
10.
10.1.
What is BigDecimal used for?
10.2.
What is the size of a BigDecimal?
10.3.
What is the limit of BigDecimal in Java?
10.4.
What operations does Java BigDecimal provide?
10.5.
How Java BigDecimal is different from double?
10.6.
How a Java BigDecimal object can be converted to a primitive data type?
11.
Conclusion
Last Updated: Apr 2, 2024
Easy

# BigDecimal Class in Java

Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

## Introduction

In Java, precision and accuracy are vital when dealing with numerical values, especially in financial and scientific applications. The BigDecimal class offers a solution by providing arbitrary-precision arithmetic. Unlike primitive data types like float and double, which have limited precision and can suffer from rounding errors, BigDecimal handles numbers with exact precision. In this blog, we will explore the functionality and usage of the BigDecimal class in Java,

## What is Java BigDecimal?

Java provides a class called BigDecimal which includes some operations to perform numerical calculations. By BigDecimal class, numerical computations become efficient and accurate.

The BigDecimal class in Java includes a 32-bit integer scale and an arbitrary precision integer scale. When the scale is greater than or equal to zero, it represents the number of digits to the right of the decimal point.

If the unscaled value of the number is multiplied by ten and raised to the power of the negative scale, the resulting value will be less than zero. Methods and Objects of the BigDecimal class can be used for Addition, Subtraction, Multiplication, Division, Comparison, Scaling, Rounding, and Conversion.

Also see, Duck Number in Java and Hashcode Method in Java.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

## Examples of Java BigDecimal

### 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

### 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);  }}``

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

### 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);    }}``

Output:

``````Original ninja_value: 3.14159265358979323846
Rounded ninja_value: 3.142``````

## Why use Java BigDecimal

• 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 Java BigDecimal

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

### 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);   }}``

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

Here are some important methods everyone should read:

1. BigDecimal(String val): This constructor creates a new BigDecimal object from a passed string.

2. add(BigDecimal val): This method returns a BigDecimal object by the addition of two BigDecimal objects.

3. subtract(BigDecimal val): This method returns a BigDecimal object by subtraction in two BigDecimal objects.

4. multiply(BigDecimal val): This method returns a BigDecimal object by multiplication of two BigDecimal objects.

5. divide(BigDecimal divisor): This method returns a BigDecimal object by division of two BigDecimal objects.

6. 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.

7. compareTo(BigDecimal val): This method compares the BigDecimal object with the BigDecimal val.

8. equals(Object obj): This method compares the BigDecimal object with the specified object for equality.

9. doubleValue(): This method converts the BigDecimal object to a double value.

10. toString(): This method type-casts to string data type value.

11. intValue(): This method converts a BigDecimal object to an int value.

12. longValue(): This method converts a BigDecimal object to a long value.

13. negate(): This method returns a BigDecimal object whose value is the negation of a BigDecimal object.

14. abs(): This method returns a BigDecimal object whose value is the absolute value of a BigDecimal object.

15. stripTrailingZeros(): This method returns a BigDecimal object with all trailing zeros removed from a fractional part of the value.

16. 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.

17. float floatValue​(): Returns the float value equivalent to the current BigDecimal object. This conversion may involve rounding or truncation.

18. int hashCode​(): Computes a hash code for the BigDecimal object. It's typically used when storing objects in hash-based collections like HashMap.

19. 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.

20. 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.

21. long longValue​(): Returns the long value of the current BigDecimal object after truncating any decimal digits. Similar to intValue(), but for long type.

22. 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.

23. BigDecimal max​(BigDecimal val): Returns the larger of the current BigDecimal object and the specified val.

24. BigDecimal min​(BigDecimal val): Returns the smaller of the current BigDecimal object and the specified val.

25. 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.

## Pros of BigDecimal 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.

## Cons of BigDecimal 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.

### What is BigDecimal used for?

BigDecimal in Java is used for precise decimal arithmetic, especially in financial, scientific, and any situation requiring high precision with decimal numbers.

### 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 is the limit of BigDecimal in Java?

The practical limit of a BigDecimal in Java is determined by the available memory, but it can represent extremely large, potentially exceeding trillions or more.

### 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.

## 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.

Do check out The Interview Guide for Product Based Companies, as well as some of the Popular Interview Problems from Top companies like AmazonAdobeGoogleUberMicrosoft, etc., on Coding Ninjas Studio.

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMS, and System Design, etc. as well as some Contests, Test SeriesInterview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.