round double value - Android java.lang

Android examples for java.lang:Math

Description

round double value

Demo Code


//package com.java2s;
import java.math.BigDecimal;

public class Main {
    public static double round(double val, int roundTo) {

        /*/*from ww  w.  j a v  a  2s .c o m*/
         * double multiPlier = java.lang.Math.pow( 10, roundTo);
         * 
         * float fl = (float) (java.lang.Math.round(val * multiPlier) /
         * multiPlier);
         * 
         * return fl;
         */

        BigDecimal bigDecimal = new BigDecimal(Double.toString(val));
        try {
            bigDecimal = bigDecimal.setScale(roundTo,
                    BigDecimal.ROUND_UNNECESSARY);
        } catch (ArithmeticException e) {
            e.printStackTrace();

            bigDecimal = bigDecimal.setScale(roundTo,
                    BigDecimal.ROUND_HALF_EVEN);
        }
        return bigDecimal.doubleValue();

    }
}

Related Tutorials