Round up BigDecimal to Integer value

Rodrigo Martinez picture Rodrigo Martinez · Sep 29, 2014 · Viewed 34.9k times · Source

I have a BigDecimal which value is 450.90, I want to round up to next hole integer value, and then print the Integer value without any decimal points, like this;

Val: 450.90 -> Rounded: 451.00 -> Output: 451

Val: 100.00001 -> Rounded: 101.00000 Output: 101

Checked some solutions but I'm not getting the expected result, heres my code;

BigDecimal value = new BigDecimal(450.90);
value.setScale(0, RoundingMode.HALF_UP); //Also tried with RoundingMode.UP
return value.intValue();

Thanks!

Answer

T.J. Crowder picture T.J. Crowder · Sep 29, 2014

setScale returns a new BigDecimal with the result, it doesn't change the instance you call it on. So assign the return value back to value:

value = value.setScale(0, RoundingMode.UP);

Live Example

I also changed it to RoundingMode.UP because you said you always wanted to round up. But depending on your needs, you might want RoundingMode.CEILING instead; it depends on what you want -451.2 to become (-452 [UP] or -451 [CEILING]). See RoundingMode for more.