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

`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

`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

`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:

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

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

**Frequently Asked Questions**

### 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 Amazon, Adobe, Google, Uber, Microsoft, etc., on Coding Ninjas Studio.

Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, and System Design, etc. as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.