Provide (relatively) precise division on double, except when the situation occurs when the endless, accurate to 10 decimal point, after the figures are rounded. - Java java.lang

Java examples for java.lang:double

Description

Provide (relatively) precise division on double, except when the situation occurs when the endless, accurate to 10 decimal point, after the figures are rounded.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        double v1 = 2.45678;
        double v2 = 2.45678;
        System.out.println(div(v1, v2));
    }/*from   www  .ja v  a2  s . c  o  m*/

    /**
     * The default precision division.
     */
    private static final int DEF_DIV_SCALE = 16;

    /**
     * Provide (relatively) precise division, except when the situation occurs
     * when the endless, accurate to 10 decimal point, after the figures are
     * rounded.
     *
     * @param v1
     * @param v2
     * @return
     */
    public static double div(double v1, double v2) {
        return div(v1, v2, DEF_DIV_SCALE);
    }

    /**
     * Provide (relatively) precise division, except when the situation occurs
     * when the endless, accurate to 10 decimal point, after the figures are
     * rounded.
     *
     * @param v1
     * @param v2
     * @return
     */
    public static double div(String v1, String v2) {
        java.math.BigDecimal b1 = new java.math.BigDecimal(v1);
        java.math.BigDecimal b2 = new java.math.BigDecimal(v2);
        return b1.divide(b2, DEF_DIV_SCALE,
                java.math.BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * Providing (relatively) accurate division. When occurrence except endless,
     * specify the scale parameter accuracy, after rounding numbers.
     *
     * @param v1
     * @param v2
     * @param scale?
     * @return
     */
    public static double div(double v1, double v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The   scale   must   be   a   positive   integer   or   zero");
        }
        java.math.BigDecimal b1 = new java.math.BigDecimal(
                Double.toString(v1));
        java.math.BigDecimal b2 = new java.math.BigDecimal(
                Double.toString(v2));
        return b1.divide(b2, scale, java.math.BigDecimal.ROUND_HALF_UP)
                .doubleValue();
    }
}

Related Tutorials