문제

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.

도움이 되었습니까?

해결책

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)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top