As you may have encountered, float is not accurate when calculating certain values.
For example, the following conditions:
Calculation is inaccurate
Package com.nicchagil.study.java.demo.No10float calculation. No01 inaccurate examples; Public class Call { publicstaticvoid main (string[] args) { System.out.println ( 0.08f + 0.01f);} }
Print:
0.089999996
Use BigDecimal instead of calculation
If you need to calculate float accurately, one way is to use BigDecimal to calculate, see the following tool classes:
ImportJava.math.BigDecimal; Public classFloatcalculator {/*** <p>add</p> *@paramA *@paramb *@return */ Public Static floatAddfloatAfloatb) {BigDecimal B1=NewBigDecimal (A + "")); BigDecimal B2=NewBigDecimal (b + "")); floatf =B1.add (B2). Floatvalue (); returnF; } /*** <p>subtract</p> *@paramA *@paramb *@return */ Public Static floatSubtractfloatAfloatb) {BigDecimal B1=NewBigDecimal (A + "")); BigDecimal B2=NewBigDecimal (b + "")); floatf =b1.subtract (B2). Floatvalue (); returnF; } /*** <p>multiply</p> *@paramA *@paramb *@return */ Public Static floatMultiplyfloatAfloatb) {BigDecimal B1=NewBigDecimal (A + "")); BigDecimal B2=NewBigDecimal (b + "")); floatf =b1.multiply (B2). Floatvalue (); returnF; } /*** <p>divide</p> * <p> when an infinite loop decimal is not divisible, rounded to the nearest side (distance), unless both sides (the distance) are equal, if so, rounded up, 1.55 retains one decimal result for 1.6& Lt;/p> *@paramA *@paramb *@return */ Public Static floatDividefloatAfloatb) {returnDivide (A, B, 2, BIGDECIMAL.ROUND_HALF_UP); } /*** <p>divide</p> *@paramA *@paramb *@paramScale *@paramRoundingmode *@return */ Public Static floatDividefloatAfloatBintScaleintRoundingmode) { /** When dividing by BigDecimal's divide method, an exception is thrown, as follows: * java.lang.arithmeticexception:non-terminating decimal Exp Ansion; No exact representable decimal result. At Java.math.BigDecimal.divide (Unknown Source) * Solution: Just set the exact decimal point divide (xxxxx,2, bigdecimal.round_half_even) for divide * Bigdecimal.round_half_up: Rounded to the nearest side (distance), unless both sides (distance) are equal, if so, rounded up, 1.55 retains one decimal result for 1.6*/BigDecimal B1=NewBigDecimal (A + "")); BigDecimal B2=NewBigDecimal (b + "")); floatf =b1.divide (B2, scale, Roundingmode). Floatvalue (); returnF; } }
"Java" float calculation is inaccurate