Strange things about adding Java double

Source: Internet
Author: User

Strange things about adding Java double

Question:
Compile and run the following program to see what?
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 are not mistaken! The result is indeed
0.060000000000000005
0.5800000000000001
401.49999999999994
1.2329999999999999

The float and double types of simple floating point numbers in Java cannot be computed. Not only Java, but also in many other programming languages. In most cases, the calculation results are accurate, but you can try multiple times (you can do a loop) to try out errors similar to the above. Now we finally understand why we need BCD code.
This problem is quite serious. If you have 9.999999999999 yuan, your computer will not think you can buy 10 yuan of goods.
Some Programming Languages provide special currency types to handle this situation, but Java does not. Now let's take a look at how to solve this problem.

Rounding
Our first response was rounding. The round method in the math class cannot be set to retain a few decimal places. We can only keep two places like this ):
Public double round (double value ){
Return math. Round (value * 100)/100.0;
}

Unfortunately, the code above does not work normally. If you pass 4.015 to this method, it will return 4.01 instead of 4.02, as we can see above
4.015*100 = 401.49999999999994
Therefore, if we want to perform precise rounding, we cannot use simple types for any operation.
Java. Text. decimalformat cannot solve this problem either:
System. Out. println (New java. Text. decimalformat ("0.00"). Format (4.025 ));
The output is 4.02

Bigdecimal
This principle is also mentioned in objective java. Float and double can only be used for scientific computing or engineering computing. In commercial computing, java. Math. bigdecimal is used. Bigdecimal has a total of four creation methods. We don't care about the two that can be created using biginteger. There are two other methods:
Bigdecimal (double Val)
Translates a double into a bigdecimal.
Bigdecimal (string Val)
Translates the string repre sentation of a bigdecimal into a bigdecimal.

The Brief description of the above API is quite clear, and it is usually easier to use the above one. We may use it if we don't want it. What's the problem? When a problem occurs, the detailed description of the above method is as follows:
Note: The results of this constructor can be somewhat unpredictable. One might assume that new bigdecimal (. 1) is exactly equal to. 1, but it is actually equal to. 1000000000000000055511151231257827021181583404541015625.
This is so because. 1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length ). thus, the long value that is being passed in to the constructor
Is not exactly equal to. 1, appearances nonwithstanding.
The (string) constructor, on the other hand, is perfectly predictable: New bigdecimal (". 1 ") is exactly equal. 1, as one wocould CT. therefore, it is generally recommended that the (string) constructor
Be used in preference to this one.
Terrible. 1,
It turns out that if we need precise calculation, we have to use string to create bigdecimal! The example in objective Java uses string to create bigdecimal, but this is not emphasized in the book. This may be a small mistake.

Solution
Now we can solve this problem. The principle is to use bigdecimal and must use string to create it.
But imagine, if we want to do an addition operation, we need to convert two floating point numbers into strings, and then convert them into bigdecimal. Call the add method on one of them and input another as a parameter, then convert the result of the operation (bigdecimal) to a floating point number. Can you endure this cumbersome process? The following provides a tool class Arith to simplify operations. 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)

Appendix

Source File Arith. Java:

Import java. Math. bigdecimal;
/**
* Because Java's simple types cannot accurately perform floating-point operations, this tool provides
* A real floating point number operation, 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 (){
}

/**
* Provides precise addition operations.
* @ Param V1 add count
* @ Param V2 addend
* @ Return the sum of the 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 ();
}

/**
* Provides precise subtraction operations.
* @ Param V1 subtrahend
* @ Param V2 subtrahend
* @ Return Difference Between 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 ();
}

/**
* Provides precise multiplication.
* @ Param V1 Multiplier
* @ 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 ();
}

/**
* Provides (relatively) accurate Division operations, accurate
* 10 digits after the decimal point, and the digits after the decimal point are rounded down.
* @ Param V1 Divisor
* @ Param V2 Divisor
* @ Return parameter vendors
*/

Public static double Div (double V1, double V2 ){
Return Div (V1, V2, def_div_scale );
}

/**
* Provides (relatively) accurate Division operations. In case of division, the scale parameter indicates
* Set the precision. The number is rounded down.
* @ Param V1 Divisor
* @ Param V2 Divisor
* @ Param scale indicates the number of digits after the decimal point.
* @ Return parameter vendors
*/

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 ();
}

/**
* Provides precise rounding of decimal places.
* @ Param V refers to the number rounded up.
* @ Param scale: number of digits after the decimal point
* @ Return returns the result after rounding.
*/

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 ();
}
};

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.