Why if I use BigDecimal
in this case, I don't get the expected result?
double value1 = 5.68;
double value2 = 2.45;
System.out.println(BigDecimal.valueOf(value1 + value2));
EXIT:
8.129999999999999
EXPECTED:
8.13
Why if I use BigDecimal
in this case, I don't get the expected result?
double value1 = 5.68;
double value2 = 2.45;
System.out.println(BigDecimal.valueOf(value1 + value2));
8.129999999999999
8.13
What happens is that you are doing the sum of the
double
not of theBigDecimal
I recommend this instead
In this way each number is first converted into a
BigDecimal
before performing the addition.Since the operator
+
does not work withBigDecimal
the method must be used.add()
insteadWhen using
BigDecimal
, it's a good idea to always use constructors and methods that don't use the typedouble
, since, as I assume you already know, the typedouble
doesn't have exact representations for many numbers that have an exact representation in base 10.For your example, you could use:
or maybe:
or this other:
Note that there is a version of these constructors with an additional parameter
MathContext
, which allows you to select the rounding mode.Since the question is about rounding using
BigDecimal
, you should only use theBigDecimal#setScale(int, RoundingMode)
:The result will be:
You can see an example of this running on ideone .
Obviously, it doesn't mean that this is the way to proceed with decimal operations. It would be best to follow the example given in @ninjalj's answer , where if you are going to use decimal numbers, initialize
BigDecimal
using strings instead ofdouble
:However, if the above operations must have a fixed number of decimal places, use
setScale
.