Domanda

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.

È stato utile?

Soluzione

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)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top