Provides precise decimals rounded handle for double values. - Java java.lang

Java examples for java.lang:double

Description

Provides precise decimals rounded handle for double values.

Demo Code


//package com.java2s;

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

    /**
     * Provides precise decimals rounded handle.
     *
     * @param v
     * @param scale
     * @return
     */
    public static double round(double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The   scale   must   be   a   positive   integer   or   zero");
        }
        java.math.BigDecimal b = new java.math.BigDecimal(
                Double.toString(v));
        java.math.BigDecimal one = new java.math.BigDecimal("1");
        return b.divide(one, scale, java.math.BigDecimal.ROUND_HALF_UP)
                .doubleValue();
    }

    /**
     * Provides precise decimals rounded handle.
     *
     * @param v
     * @param scale
     * @return
     */
    public static double round(String v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The   scale   must   be   a   positive   integer   or   zero");
        }
        java.math.BigDecimal b = new java.math.BigDecimal(v);
        java.math.BigDecimal one = new java.math.BigDecimal("1");
        return b.divide(one, scale, java.math.BigDecimal.ROUND_HALF_UP)
                .doubleValue();
    }
}

Related Tutorials