Code example for MathContext

0
 
    public void testAddMathContextNonTrivial() { 
        MathContext mc;
        BigDecimal a, b, res;
 
        mc = new MathContext(17, RoundingMode.FLOOR);
        a = new BigDecimal("123456789012345.678");
        b = new BigDecimal("100000000000000.009");
        assertEquals("incorrect value", "123456789012345.67",
                a.round(mc).toString());
        assertEquals("incorrect value", "100000000000000.00",
                b.round(mc).toString());
        assertEquals("incorrect value", "223456789012345.67",
                a.round(mc).add(b.round(mc)).toString());
        res = a.add(b, mc);
        assertEquals("incorrect value", "223456789012345.68", res.toString());
 
        mc = new MathContext(33, RoundingMode.UNNECESSARY);
        a = new BigDecimal("1234567890123456789012345678.9012395");
        b = new BigDecimal("1000000000000000090000000000.0000005");
        res = a.add(b, mc);