Java basics (calculation of large numbers and calculation of floating-point data)

1. Calculation of large numbers

BigInteger can be used to solve the problem of data overflow , allowing data beyond the Integer range to be calculated

The maximum range is unclear. In theory, it can represent a large number of wireless, as long as the computer memory is large enough.

Code example:

 //大数计算,解决数据的溢出问题
BigInteger b1=new BigInteger("2149992344");
BigInteger b2=new BigInteger("82784228347");
BigInteger result=b1.add(b2);
System.out.println(result);

operation result:

2. Floating-point arithmetic

Because in the operation, the float type and double are easy to lose precision

Therefore, in order to accurately represent and calculate floating point numbers, Java provides BigDecimal

Code example:

System.out.println(0.01+0.09);
//精确计算小数
BigDecimal b3=new BigDecimal("0.09");
BigDecimal b4=new BigDecimal("0.01");
BigDecimal result1=b3.add(b4);
System.out.println(result1);

operation result:

Published 75 original articles · praised 164 · 110,000 views

Guess you like

Origin blog.csdn.net/qq_41679818/article/details/93751271