Java BigDecimal Class

Using BigDecimal to perform precise calculations with floats.

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

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

Do the arithmatics:

1 pi.multiply(pi);
2 pi.add(pi);
3 pi.subtract(pi);
4 //Usage of division should also point out the precision
5 MathContext mc = new MathContext(2,BigDecimal.Round_Ceiling);
6 pi.divide(pi,mc);
7 //also works
8 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.

posted on 2016-04-12 16:24  三叁  阅读(284)  评论(0编辑  收藏  举报

导航