Solve the computing failure caused by java float double Floating Point, floatdouble
I did a community e-commerce application some time ago and found a trap ...... let me cry. Let's take a look at my path. E-commerce must be dealing with ¥, which is indispensable for computing. Because I think that float double can be directly involved in addition, subtraction, multiplication, division, and I feel that this code is foolproof and I don't want to think so much direct float * int. There was no problem with a simple test before, and it was discovered by accident after the project went online (I don't know what the company did for testing). When multiple items were selected, let's talk about the phenomenon directly. For example, in the Code, 0.1 f * A is int type. When the result of A = 1 is correct but gradually increases to A = 9, the result is equal to 0.9000000. (How much 0 forgot )... 4. This is embarrassing. At that time, Baidu looked up and said that the floating point type was inaccurate. Anyway, I am a newbie, but people have a solution. This is the focus .... in the future, do not use floating point computing, especially for the amount involved. If I don't talk about it, I will post the tool class of the computation, so the boss hasn't found it updated.
Tool class:
/**
* @ Author Mr_Peng
* @ Created.
* @ Describe: java Precision Calculation
*/
Public class ArithUtil {
Private static final int DEF_DIV_SCALE = 10;
Private ArithUtil (){}
Public static double add (double d1, double d2 ){
BigDecimal b1 = new BigDecimal (Double. toString (d1 ));
BigDecimal b2 = new BigDecimal (Double. toString (d2 ));
Return b1.add (b2). doubleValue ();
}
Public static double sub (double d1, double d2 ){
BigDecimal b1 = new BigDecimal (Double. toString (d1 ));
BigDecimal b2 = new BigDecimal (Double. toString (d2 ));
Return b1.subtract (b2). doubleValue ();
}
Public static double mul (double d1, double d2 ){
BigDecimal b1 = new BigDecimal (Double. toString (d1 ));
BigDecimal b2 = new BigDecimal (Double. toString (d2 ));
Return b1.multiply (b2). doubleValue ();
}
Public static double div (double d1, double d2 ){
Return div (d1, d2, DEF_DIV_SCALE );
}
Public static double div (double d1, double d2, int scale ){
If (scale <0 ){
Throw new IllegalArgumentException ("The scale must be a positive integer or zero ");
}
BigDecimal b1 = new BigDecimal (Double. toString (d1 ));
BigDecimal b2 = new BigDecimal (Double. toString (d2 ));
Return b1.divide (b2, scale, BigDecimal. ROUND_HALF_UP). doubleValue ();
}
}
Proof: It is true and valid, and the computation result is 100% accurate without any additional decimal places.