I have the following function that is used to round a double value in Java:
public static double round(double d, int decimalPlace) {
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
As input, this function is receiving these values:
double d = 7.3149999999999995;
int decimalPlace = 2
But, when the function returns, the value returned is 7.31, instead of 7.32.
I searched on the docs to see why the bd.SetScale is with that behavior, but with no success.
Does anybody could me explain why is this happening?
Thanks a lot!!
It’s obeying the documented behaviour 🙂 From the docs:
And for
RoundingMode.HALF_UP:Now 7.3149999999999995 isn’t equidistant to both 7.31 and 7.32 – it’s closer to 7.31, so that’s the result.
The difference between
HALF_UPandHALF_DOWNwould only be seen if the original value were exactly 7.315, i.e. half way between the two.As an aside, to make sure you get exactly the number you’d expect to start with, I’d suggest using a
String. For example:isn’t the same as:
Converting from
doubletoBigDecimalis usually a sign that you’ve got something wrong, and you should be using one type consistently throughout.