On the arithmetic precision of double type in Java

Source: Internet
Author: User
Tags arithmetic mul

(Its tool class is in the project Arith Util )

Original URL:http://blog.csdn.net/pttaag/article/details/5912171

First, the previous 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 have not read wrong! The result is indeed
0.060000000000000005
0.5800000000000001
401.49999999999994
1.2329999999999999

Simple floating-point type float and double in Java are not capable of operation.
This problem is quite serious, if you have 9.999999999999 yuan, your computer will not think you can buy a product of ten yuan.
Special currency types are available in some programming languages to handle this situation, but Java does not. Now let's look at how to solve this problem.

rounding
Our first reaction was to do rounding. math round method cannot be set to retain several decimals, we can only like this (reserved two bits):
Public double round (double value) {
    return math.round (value*100)/100.0;
}
Unfortunately, the above code does not work properly, passing this method to 4.015 4.01 4.02
4.015*100=401.49999999999994
So if we're going to do a precise rounding, we can't do anything with a simple type
Java.text.decimalformat
System.out.println (New java.text.decimalformat (" 0.00 "). Format (4.025) );
output is 4.02

Now that we can solve this problem, the principle is to useBigDecimaland be sure to useStringcome tostructureBuilding.
But imagine, if we're going to do an addition, we need to convert two floating-point numbers firstString, and thenstructurecausingBigDecimal, called on one of theAddmethod, passing in another as a parameter, and then putting the result of the operation (BigDecimal) to a floating-point number. Can you endure such a tedious process? nowprovides a tool classArithto simplify the operation. It provides the following static methods, including subtraction 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 tool class source code, in fact, the cumbersome process is encapsulated to facilitate direct invocation:

ImportJava.math.BigDecimal;/*** Because Java's simple type does not accurately operate on floating-point numbers, this tool class provides fine-grained floating-point arithmetic, including subtraction and rounding. */ Publicclassarith{//Default division operation PrecisionPrivateStaticFinal intDef_div_scale = 10; //This class cannot be instantiatedPrivateArith () {}/*** provides accurate addition operations. * @paramv1 summand *@paramV2 Addend *@returntwo parameters of A and*/     PublicStaticDoubleAddDoubleV1,Doublev2) {BigDecimal B1=NewBigDecimal (double.tostring (v1)); BigDecimal B2=NewBigDecimal (Double.tostring (v2)); returnB1.add (B2). Doublevalue (); }    /*** provides accurate subtraction operations. * @paramv1 minuend *@paramv2 *@returnthe difference of two parameters*/     PublicStaticDoubleSubDoubleV1,Doublev2) {BigDecimal B1=NewBigDecimal (double.tostring (v1)); BigDecimal B2=NewBigDecimal (Double.tostring (v2)); returnb1.subtract (B2). Doublevalue (); }     /*** provides accurate multiplication operations. * @paramv1 by multiplier *@paramV2 Multiplier *@returnproduct of two parameters*/     PublicStaticDoubleMulDoubleV1,Doublev2) {BigDecimal B1=NewBigDecimal (double.tostring (v1)); BigDecimal B2=NewBigDecimal (Double.tostring (v2)); returnb1.multiply (B2). Doublevalue (); }     /*** Provide (relative) accurate division operations, when there are no more than an endless situation, accurate to * after the decimal 10 digits, after the number rounded. * @paramV1 Dividend *@paramv2 Divisor *@returntwo parameters of the quotient*/     PublicStaticDoubleDivDoubleV1,Doublev2) {        returnDiv (V1,v2,def_div_scale); }     /*** Provide (relative) accurate division operations.     When the exception occurs, the scale parameter refers to the fixed precision, and the subsequent numbers are rounded. * @paramV1 Dividend *@paramv2 Divisor *@paramthe scale representation needs to be accurate to several points after the decimal point. * @returntwo parameters of the quotient*/     PublicStaticDoubleDivDoubleV1,DoubleV2,intScale ) {        if(scale<0){            ThrowNewIllegalArgumentException ("The scale must is a positive integer or zero"); } BigDecimal B1=NewBigDecimal (double.tostring (v1)); BigDecimal B2=NewBigDecimal (Double.tostring (v2)); returnb1.divide (b2,scale,bigdecimal.round_half_up). Doublevalue (); }     /*** Provides precise rounding of decimal digits. * @paramv need to round the number *@paramA few * after the decimal point@returnresults after rounding*/     PublicStaticDoubleRoundDoubleVintScale ) {        if(scale<0){            ThrowNewIllegalArgumentException ("The scale must is a positive integer or zero"); } BigDecimal b=NewBigDecimal (double.tostring (v)); BigDecimal One=NewBigDecimal ("1"); returnb.divide (one,scale,bigdecimal.round_half_up). Doublevalue (); }}; 

On the arithmetic precision of double type in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.