Monday, October 18, 2010

Rounding the double value in java

 For rounding the double value You can use the following code . some time its require that you have to round the value of double literal .
e.g . 1) 12.34656 require to round to 12.35
        2) 165.454 to 165.5 etc .
For that case you can use following code you are require to only create object of RoundUp class with input parameter double value  and up to which decimal you have to round value.
e.g. for  fist 1) RoundUp ru=new RoundUp(12.34656,2);
                    BigDecimal roundedValue=ru.roundUP();
                    2)RoundUp ru=new RoundUp(165.454,1);
                    BigDecimal roundedValue=ru.roundUP();




 //code section
import java.math.BigDecimal;

public class RoundUp {
    private double dbl;
    private int roundUpTo;
    public RoundUp(double Value,int roundTodec)
    {
        dbl=Value;
        roundUpTo=roundTodec;
    }
      public BigDecimal roundUP()
        {
            BigDecimal bd=new BigDecimal(dbl);
            return bd.setScale(roundUpTo,BigDecimal.ROUND_UP);
        }

}

No comments:

Post a Comment