Double calculation accuracy problem in java

 

About the accuracy of the double type in Java

First case:

public class Test{     public static void main(String args[]){         System.out.println(0.05+0.01);         System.out.println(1.0-0.42);         System.out.println(4.015*100);         System. out.println(123.3/100);     } }; You read it right! The result is indeed 0.060000000000000005 0.5800000000000001 401.49999999999994 1.2329999999999999











The simple floating-point number types float and double in Java cannot be operated on.
This problem is quite serious. If you have 9.999999999999 yuan, your computer will not think that you can buy goods for 10 yuan.
In some programming languages, a special currency type is provided to handle this situation, but Java does not. Now let us see how to solve this problem.

 

Rounding
Our first reaction is to round up. The round method in the Math class cannot be set to retain several decimal places, we can only do like this (reserve two):
public double round(double value){     return Math.round(value*100)/100.0; } Very unfortunate, the above The code does not work properly. Passing 4.015 to this method will return 4.01 instead of 4.02, as we saw above 4.015*100=401.49999999999994. Therefore, if we want to round accurately, we can’t use simple types to do any operations java .text.DecimalFormat can’t solve this problem either: System.out.println(new java.text.DecimalFormat("0.00").format(4.025)); The output is 4.02







 

Now we can solve this problem, the principle is to use BigDecimal and must use String to construct.
But imagine, if we want to do an addition operation, we need to first convert two floating-point numbers to String, then construct a BigDecimal, call the add method on one of them, pass the other as a parameter, and then take the result of the operation ( BigDecimal) and then converted to a floating point number. Can you bear such a tedious process? A tool class Arith is now provided to simplify the operation. It provides the following static methods, including addition, subtraction, multiplication, division, and rounding:
public static double add(double v1,double v2)
public static double sub(double v1,double v2)
public static double mul(double v1,double v2)
public static double div (double v1,double v2)
public static double div(double v1,double v2,int scale)
public static double round(double v,int scale)

The following is the source code of the tool, which actually encapsulates the cumbersome process for direct call:

Copy code

import java.math.BigDecimal;
/**
 * Since Java's simple types cannot accurately perform operations on floating-point numbers, this tool class provides precision
 * Accurate floating-point operations, including addition, subtraction, multiplication, division, and rounding.
 */
public class Arith{
    //Default division operation precision
    private static final int DEF_DIV_SCALE = 10;
    //This class cannot be instantiated
    private Arith () {
    }
 
    /**
     * Provide precise addition operations.
     * @param v1 addendum
     * @param v2 addend
     * @return the sum of two parameters
     */
    public static double add(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }
    /**
     * Provide precise subtraction operations.
     * @param v1 minuend
     * @param v2 minus
     * @return The difference between the two parameters
     */
    public static double sub(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2).doubleValue();
    } 
    /**
     * Provide precise multiplication operations.
     * @param v1 Multiplicand
     * @param v2 multiplier
     * @return The product of two parameters
     */
    public static double mul(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2).doubleValue();
    }
 
    /**
     * Provide (relatively) accurate division operation, when the division is inexhaustible, accurate to
     * 10 digits after the decimal point, and the following figures are rounded off.
     * @param v1 dividend
     * @param v2 divisor
     * @return the quotient of the two parameters
     */
    public static double div(double v1,double v2){
        return div(v1,v2,DEF_DIV_SCALE);
    }
 
    /**
     * Provide (relatively) accurate division operation. When inexhaustible division occurs, the scale parameter refers
     * Determine the precision, and the subsequent figures will be rounded off.
     * @param v1 dividend
     * @param v2 divisor
     * @param scale means that it needs to be accurate to a few decimal places.
     * @return the quotient of the two parameters
     */
    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");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
    }
 
    /**
     * Provide accurate rounding of decimal places.
     * @param v The number that needs to be rounded
     * @param scale Keep a few digits after the decimal point
     * @return rounded result
     */
    public static double round(double v,int scale){
        if(scale<0){
            throw new IllegalArgumentException(
                "The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}; 

Guess you like

Origin blog.csdn.net/qq_33767353/article/details/100665526