divide two double values - Java java.lang

Java examples for java.lang:double

Description

divide two double values

Demo Code


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

public class Main {
    public static void main(String[] argv) throws Exception {
        double dividend = 2.45678;
        double divisor = 2.45678;
        System.out.println(div(dividend, divisor));
    }/*from   ww w .  j  a v a 2  s .  co m*/

    private static final int DEF_DIV_SCALE = 10;

    public static double div(double dividend, double divisor) {
        return div(dividend, divisor, DEF_DIV_SCALE);
    }

    public static double div(double dividend, double divisor, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(dividend));
        BigDecimal b2 = new BigDecimal(Double.toString(divisor));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}

Related Tutorials