Java's high-precision integer and high-precision decimal, java's high-precision
In actual coding, we will encounter many high-precision cases. For example, when calculating money, we need to keep high-precision decimals so that the computation will not have too many errors:
In the following code, we verify that when two float numbers are added, the result is different from our expected result. to reduce and prevent such errors, we need to use the BigInteger and BigDecimal classes for calculation.
Package com. ietree. base. number; import java. math. bigDecimal; import java. math. bigInteger; public class BigIntegerTest {public static void main (String [] args) {float f1 = 123.01f + 2.01f; // expected output: 125.02; actual output: 125.020004 System. out. println (f1); // expected output: 125.02; actual output: 125.02000000000001 System. out. println (123.01 + 2.01); System. out. println ("============================== "); // high-precision Integer test BigInteger bint1 = new BigInteger ("125"); BigInteger bint2 = new BigInteger ("999"); BigInteger tmp; // Add tmp = bint1.add (bint2 ); system. out. println ("bint1 + bint2 =" + tmp); // subtract tmp = bint2.subtract (bint1); System. out. println ("bint2-bint1 =" + tmp); // multiply tmp = bint1.multiply (bint2); System. out. println ("bint1 * bint2 =" + tmp); // select tmp = bint2.divide (bint1); System. out. println ("bint2/bint1 =" + tmp); // evaluate the remainder tmp = bint2.remainder (bint1); System. out. println ("bint2% bint1 =" + tmp); // evaluate the power tmp = bint2.pow (2); System. out. println ("bint2 quadratic =" + tmp); System. out. println ("========================================== = "); // BigDecimal bd1 = new BigDecimal (123.01); BigDecimal bd2 = new BigDecimal (2.01); BigDecimal bd; // Add bd = bd1.add (bd2); System. out. println ("bd1 + bd2 =" + bd); // subtract bd = bd1.subtract (bd2); System. out. println ("bd2-bd1 =" + bd); // multiply bd = bd1.multiply (bd2); System. out. println ("bd1 * bd2 =" + bd); // division // bd = bd1.divide (bd2); bd = bd1.divide (new BigDecimal (2.0); System. out. println ("bd1/2.0 =" + bd); // evaluate the remainder bd = bd1.remainder (bd2); System. out. println ("bd2% bd1 =" + bd); // evaluate the power bd = bd1.pow (3); System. out. println ("bd2 3rd power =" + bd); System. out. println ("========================================== = "); // number of decimal places reserved for Rounding: BigDecimal bd3 = new BigDecimal (123.01 ). setScale (5, 5); System. out. println ("bd3 =" + bd3 );}}