Provide accurate subtraction among double values. - Java java.lang

Java examples for java.lang:double

Description

Provide accurate subtraction among double values.

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(sub(v1, v2));
    }//from   w  ww. j  a  v  a2  s .  c om

    /**
     * Provide accurate subtraction.
     *
     * @param v1
     * @param v2
     * @return
     */
    public static double sub(double v1, double v2) {
        java.math.BigDecimal b1 = new java.math.BigDecimal(
                Double.toString(v1));
        java.math.BigDecimal b2 = new java.math.BigDecimal(
                Double.toString(v2));
        return b1.subtract(b2).doubleValue();
    }

    /**
     * Provide accurate subtraction.
     *
     * @param v1
     * @param v2
     * @return
     */
    public static double sub(String v1, String v2) {
        java.math.BigDecimal b1 = new java.math.BigDecimal(v1);
        java.math.BigDecimal b2 = new java.math.BigDecimal(v2);
        return b1.subtract(b2).doubleValue();
    }
}

Related Tutorials