Question

Given an integer BigDecimal (i.e., with no decimal point), how can I add .00 to it?

What I have is:

BigDecimal Add2Zeros(BigDecimal num)
{
    return num.divide(BigDecimal.ONE,2,RoundingMode.HALF_UP);
}

But it seems a bit clumsy. Is there a better / simpler / cleaner way to do that?

BTW, It is not supposed to have any impact on the argument, except for the toString() result.

Était-ce utile?

La solution

Use .setScale():

return num.setScale(2);

Note that it will NOT truncate numbers; if a number has more than 2 decimals, it will throw an ArithmeticException. (except if all decimals after the second one are 0)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top