The floating-point data types (float and double) are not as accurate to be used in the financial calculations. Therefore, Java offers a separate class “BigDecimal” to perform the operations and avoid the minimal chances of mistakes in calculations. BigDecimal class provides operations on double numbers for arithmetic, scale handling, rounding, comparison, format conversion, and hashing. It can handle very large and very small floating-point numbers with great precision but compensating with the time complexity a bit. BigDecimal provides numerous methods to be implemented upon. In this article, we’ll be discussing the basic arithmetic operations which can be performed on BigDecimal and also performing the same operations between BigDecimal and primitive data types such as int, short, long, etc.
Additon of num1 and num2 = 60.7299028768 Subtraction of num1 and num2 = -30.0269771232 Multiplication of num1 and num2 = 696.625437067096192
Note that the accuracy of the operations is very high. Now performing division on the same set of numbers in the below example as follows:
This error occurred because the division of the two numbers was non-terminating, and we know that BigDecimal is introduced to provide the maximum accuracy. Hence, it produces an error. We will be rectifying the same in the next code where we will be dividing the same numbers, but now the data type is double, and it should not produce any error and gives some answers.
Division of num1 and num2 = 2.955968454874647
Until now, we’ve performed the arithmetic operations on two BigDecimal objects, and now we shall try to do the same thing with the primitive data types.So here we go.
This is because BigDecimal only allows the operation to be performed only on BigDecimal objects. Therefore, we need to convert our primitive data type variable to the object of BigDecimal using the constructor of BigDecimal Class. The above conflict is resolved in the below code as follows.
Addition of num1 and num2 = 27
What is happening here is that we are creating a new object of class BigDecimal with a value same as num2 and we are directly passing the object created through the constructor to the argument of add() method. And we get our required answer. The arithmetic operations between BigDecimal and int are shown below.
Addition of num1 and num2 = 27 Subtraction of num1 and num2 = -3 Multiplication of num1 and num2 = 180 Division of num1 and num2 = 0.8
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.