Java BigDecimal Class

时间:2022-09-10 21:00:53

Using BigDecimal to perform precise calculations with floats.

BigDecimal is a class type. So declare/construct one BigDecimal is in the form like:

 BigDecimal pi = new BigDecimal("3.14159265358979323846");
BigDecimal pi = new BigDecimal(3.14);
BigDecimal pi = new BigDecimal(3.14f);
BigDecimal pi = new BigDecimal(3);

Do the arithmatics:

 pi.multiply(pi);
pi.add(pi);
pi.subtract(pi);
//Usage of division should also point out the precision
MathContext mc = new MathContext(2,BigDecimal.Round_Ceiling);
pi.divide(pi,mc);
//also works
pi.divide(pi,2,BigDecimal.Round_Ceiling);

Compare 2 BigDecimals:

//f<l, f=l, f>l
pi.compareTo(pi);

Print BigDecimals:

System.out.println(pi);

Addendum:

So why normal float can not represent floats precisely? It's because computer represents numbers in radix 2, it can represent floats precisely like 1*2^-1 + 1*2^-3, which is 0.101b = 0.625d. It is known that some numbers can not represent precisely in radix 10, like 1/3b = 0.3d. However, according to 1/3 = 1*3^-1, 1/3d = 0.1r3 precisely.