We know that floating-point numbers cannot be accurately represented in a computer, for example, 0.1 is only represented as an approximation in a computer, so the results are unpredictable when dealing with the number of points.
In the case of numeric operations, if there are double or float-type floating-point numbers participating in the calculation, there are occasional instances of inaccurate computations. As the following sample code:
Package ex; Public class bigdecitest { publicstaticvoid 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); }}
The result of the above code execution is as follows:
0.0600000000000000050.5800000000000001401.499999999999941.2329999999999999
In most cases, the results of double and float calculations are accurate, but in some systems with high precision requirements, this problem is very serious.
In effective Java, the principle is that float and double can only be used for scientific calculations or engineering calculations, But in business computing we have to use java.math.BigDecimal, we can solve the above problem by using the BigDecimal class, the example code is as follows:
Packageex;Importjava.math.*; Public classBigdecimaldemo { Public Static voidMain (string[] args) {System.out.println (Arithutil.add (0.01, 0.05)); System.out.println (Arithutil.sub (1.0, 0.42)); System.out.println (Arithutil.mul (4.015, 100)); System.out.println (Arithutil.div (123.3, 100)); }}classarithutil{Private Static Final intdef_div_scale=10; PrivateArithutil () {} Public Static DoubleAddDoubleD1,DoubleD2) {BigDecimal B1=NewBigDecimal (double.tostring (D1)); BigDecimal B2=NewBigDecimal (double.tostring (D2)); returnB1.add (B2). Doublevalue (); } Public Static DoubleSubDoubleD1,DoubleD2) {BigDecimal B1=NewBigDecimal (double.tostring (D1)); BigDecimal B2=NewBigDecimal (double.tostring (D2)); returnb1.subtract (B2). Doublevalue (); } Public Static DoubleMulDoubleD1,DoubleD2) {BigDecimal B1=NewBigDecimal (double.tostring (D1)); BigDecimal B2=NewBigDecimal (double.tostring (D2)); returnb1.multiply (B2). Doublevalue (); } Public Static DoubleDivDoubleD1,DoubleD2) { returnDiv (D1,d2,def_div_scale); } Public Static DoubleDivDoubleD1,DoubleD2,intScale ) { if(scale<0){ Throw NewIllegalArgumentException ("The scale must is a positive integer or zero"); } BigDecimal B1=NewBigDecimal (double.tostring (D1)); BigDecimal B2=NewBigDecimal (double.tostring (D2)); returnb1.divide (b2,scale,bigdecimal.round_half_up). Doublevalue (); } }
The results of the operation are as follows:
0.060.58401.51.233
Please refer to the API documentation for details.
How to solve the problem of double and float accuracy not allowed in Java