Home  >  Core Java

Example of MathContext in Java

By Arvind Rai, March 23, 2013
MathContext belongs to the package java.math. It is used for numerical calculation. It specifies precision and rounding mode. In case of BigDecimal, we provide the object of MathContext. RoundingMode is a enum. It has the values like
RoundingMode.CEILING
RoundingMode.DOWN
RoundingMode.FLOOR
RoundingMode.HALF_EVEN
RoundingMode.HALF_UP
RoundingMode.UP 
Using RoundingMode, we craete the object of MathContext as
new MathContext(2, RoundingMode.CEILING)
 
Find the sample example below
MathContextTest.java
package com.concretepage;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class MathContextTest {
    public static void main(String[] args) {
        System.out.println(new BigDecimal("354.765", new MathContext(2, RoundingMode.CEILING)));
        System.out.println(new BigDecimal("354.765", new MathContext(2, RoundingMode.DOWN)));
        System.out.println(new BigDecimal("354.765", new MathContext(1, RoundingMode.FLOOR)));
        System.out.println(new BigDecimal("354.765", new MathContext(3, RoundingMode.HALF_EVEN)));
        System.out.println(new BigDecimal("354.765", new MathContext(3, RoundingMode.HALF_UP)));
        System.out.println(new BigDecimal("354.765", new MathContext(1, RoundingMode.UP)));
    }
}
Output
3.6E+2
3.5E+2
3E+2
355
355
4E+2 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us