divide two double via BigDecimal and control rounding - Java java.math

Java examples for java.math:BigDecimal Calculation

Description

divide two double via BigDecimal and control rounding

Demo Code


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

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  w ww.  j av a2s .  co  m*/

    private static final int DEF_DIV_SCALE = 25;

    public static double div(double v1, double v2) {
        return div(v1, v2, DEF_DIV_SCALE);
    }

    public static double div(double v1, double v2, int scale) {

        if (v2 == 0d) {
            return 0d;
        }

        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }

        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));

        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();

    }
}

Related Tutorials