I have the following code.
BigDecimal num = new BigDecimal(3.2);
System.out.println(num);
Expected:
3.2
Departure.
3.20000000000000017763568394002504646778106689453125
Therefore.
BigDecimal num = new BigDecimal(3.2);
BigDecimal num1 = new BigDecimal(2);
System.out.println(num.add(num1));
Expected:
5.2
Departure.
5.20000000000000017763568394002504646778106689453125
I don't understand how to perform calculations with basic operations in Java, I don't know if there is another library or another way to do this.
BigDecimal
is the class offered by the Java JDK to work with decimal numbers more exactly. The problem you have arises because you are initializing your instances ofBigDecimal
usingdouble
, and the latter suffers from the classic floating point operations problem. This issue is explained in more detail in this question and its answers .In Java, in order for you to use the potential of
BigDecimal
using decimal numbers, you must use the constructor that receives a text string:In case you are initializing a variable
BigDecimal
with adouble
because you have no other output eg when using Apache POI and you get the numeric value of a cell, then what you should do is round the value of your number to a fixed number of decimal places:When you use
int
(integer) orlong
(longint), there is no problem initializing your variable:Related: