round double value via BigDecimal - Java java.math

Java examples for java.math:BigDecimal

Description

round double value via BigDecimal

Demo Code


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

public class Main {
    public static void main(String[] argv) throws Exception {
        double v = 2.45678;
        int scale = 2;
        System.out.println(round(v, scale));
    }/*  w ww.  j a  v a 2s  .com*/

    public static double round(double v, int scale) {

        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        return b.divide(BigDecimal.ONE, scale, BigDecimal.ROUND_HALF_UP)
                .doubleValue();

    }
}

Related Tutorials