round two double values - Java java.lang

Java examples for java.lang:double

Description

round two double values

Demo Code


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

public class Main {
    public static void main(String[] argv) throws Exception {
        double value = 2.45678;
        int scale = 2;
        System.out.println(round(value, scale));
    }/*ww  w  .  ja v a2s .  co m*/

    public static double round(double value, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal bd = new BigDecimal(Double.toString(value));
        return bd.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();

    }
}

Related Tutorials