Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round up BigDecimal to Integer value

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!

like image 220
Rodrigo Martinez Avatar asked Sep 29 '14 14:09

Rodrigo Martinez


People also ask

How do I round off BigDecimal value?

math. BigDecimal. round(MathContext m) is an inbuilt method in Java that returns a BigDecimal value rounded according to the MathContext settings. If the precision setting is 0 then no rounding takes place.

How do I convert BigDecimal to integer?

intValue()converts this BigDecimal to an int. This conversion is analogous to the narrowing primitive conversion from double to short. Any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in an int, only the low-order 32 bits are returned.

Can we convert BigDecimal to integer in Java?

The java. math. BigDecimal. intValue() is an in-built function which converts this BigDecimal to an integer value.

How do I Ceil BigDecimal in Java?

use the Math. ceil() function. The method ceil gives the smallest integer that is greater than or equal to the argument.


1 Answers

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.

like image 146
T.J. Crowder Avatar answered Sep 23 '22 07:09

T.J. Crowder