Precision loss occurs when the float and double types perform subtraction. This problem is mainly caused by the widespread use of binary in computers. This is a record to prevent future forgetting.
Public static void main (string [] ARGs) {float a = 2.1f; float B = 2.0f; float c = A-B; system. out. println ("a-B =" + C);} // output: A-B = 0.099999905
In this case, you need to use the bigdecimal class
Bigdecimal add (bigdecimalaugend) addition operation
Bigdecimal subtract (bigdecimal subtrahend) subtraction operation
Bigdecimal multiply (bigdecimal multiplicand) Multiplication
Bigdecimal divide (bigdecimal divisor) division operation
Public static void main (string [] ARGs) {float a = 2.1f; float B = 2.0f; bigdecimal a1 = new bigdecimal (float. tostring (a); bigdecimal b1 = new bigdecimal (float. tostring (B); float C1 = a1.subtract (B1 ). floatvalue (); system. out. println ("a1-b1 =" + C1);} // output: a1-b1 = 0.1
Detailed principle reference http://www.blogjava.net/jelver/articles/340038.html
This article is from the blog "plug on the name of pigs", please be sure to keep this source http://zuohao1990.blog.51cto.com/6057850/1560642
Precision loss in float and double subtraction operations