Round up BigDecimal to Integer value

41,128

Solution 1

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.

Solution 2

use:

value.setScale(0, RoundingMode.CEILING);

Solution 3

From method description:

Note that since BigDecimal objects are immutable, calls of setScale method do not result in the original object being modified, contrary to the usual convention of having methods named setX mutate field X. Instead, setScale returns an object with the proper scale; the returned object may or may not be newly allocated.

public void test() {
  BigDecimal value = new BigDecimal(450.90);
  System.out.println(value.setScale(0, RoundingMode.HALF_UP)); // prints 451
}

Solution 4

you need to use the returned value

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

note that BigDecimal is invariant

Scaling/rounding operations (setScale and round) return a BigDecimal whose value is approximately (or exactly) equal to that of the operand, but whose scale or precision is the specified value; that is, they increase or decrease the precision of the stored number with minimal effect on its value.

Share:
41,128
Rodrigo Martinez
Author by

Rodrigo Martinez

Updated on September 30, 2020

Comments

  • Rodrigo Martinez
    Rodrigo Martinez over 3 years

    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!