Skip to Content
avatar image
Former Member

Big decimal rounding

Hi,

I have a bigdecimal numbers 5.5, 1.2, and 0.5. I want to convert all these numbers as 6, 2, 1.

Could you please tell how to achieve this?. I tried with ceiling, round_up, but I didnt get exact result.

Thanks-in-advance.

Sunita.

Add comment
10|10000 characters needed characters exceeded

  • Get RSS Feed

1 Answer

  • Oct 18, 2006 at 12:00 AM

    Please try this.

    
    import java.math.*;
    
    public class TestBigD {
    
    	public static void main(final String[] args) {
    
    		BigDecimal bd = new BigDecimal("12.2");
    		BigInteger bi = new BigInteger("0");
    
    		bi = bd.setScale(0, BigDecimal.ROUND_CEILING).toBigInteger();
    		System.out.println(bi);
    	}
    
    }
    
    

    Regards,

    Rich Heilman

    Add comment
    10|10000 characters needed characters exceeded

    • Neither do I 😊

      In this case, BD is a BigDecimal which has a value of 12.2. I created an instance of BigInteger call BI, so we use the setScale method of BigDecimal to set how we want to round this value, notice the ROUND_CEILING, of course this will always round up regardless if it is less than 5 or greater, then it is passing the rounded value to our BigInteger bi. Then simply writing out bi.

      Regards,

      Rich Heilman