Java BigDecimal: Precise Decimal Numbers
The BigDecimal class in Java is used for precise representation and calculation of decimal numbers. It offers various methods to perform basic arithmetic operations like addition, subtraction, multiplication, and division, as well as supporting comparison operations and rounding.
Here are some common examples of how BigDecimal is typically used:
- Create a BigDecimal object.
- BigDecimal num1 = new BigDecimal(“10.25”); // Creating a BigDecimal object using a string
BigDecimal num2 = BigDecimal.valueOf(5.75); // Creating a BigDecimal object using a double value - Perform basic arithmetic operations.
- BigDecimal sum = num1 added to num2;
BigDecimal difference = num1 subtracted by num2;
BigDecimal product = num1 multiplied by num2;
BigDecimal quotient = num1 divided by num2, with 2 decimal places rounded up. - Comparison operation:
- int result = num1.compareTo(num2); // Compares the sizes of two BigDecimal objects, returning -1, 0, or 1
boolean isEqual = num1.equals(num2); // Checks if two BigDecimal objects are equal
boolean isGreater = num1.compareTo(num2) > 0; // Determines if num1 is greater than num2
boolean isLess = num1.compareTo(num2) < 0; // Determines if num1 is less than num2 - Round to the nearest whole number.
- BigDecimal rounded = num1.setScale(0, RoundingMode.CEILING);
BigDecimal truncated = num1.setScale(0, RoundingMode.FLOOR);
It is important to note that since BigDecimal is an immutable class, all operations will return a new BigDecimal object. Therefore, when performing consecutive calculations, the result should be assigned to a new variable.
Additionally, due to the slower nature of BigDecimal operations, it may be worth considering using BigDecimal in certain scenarios that require precise calculations to ensure accuracy.