Pages

Wednesday, August 8, 2012

How to operate with big integer, big decimal

Sometimes the range of long, double  etc... becomes inadequate for certain mathematical operations. So  java provides a way to handle this problem by introducing BigInteger and Bigdecimal. These are very useful when the programmer needs to calculate big values.  Below examples shows how to work with big integer and big decimal.

First lets see an example of big integer.

BigInteger b1  = new BigInteger("293847293847938798");

BigInteger b2  = BigInteger.valueOf(1298L);
b1 = b1.add(b2);
b1 = b1.subtract(b2);
b1 = b1.multiply(b2);
b1 = b1.divide(b2);
b1 = b1.negete();

int exponent = 3;
b1=b1.pow(exponent);

Now lets see an example of big decimal.

Bigdecimal b1  = new Bigdecimal("348950394.943859438");

Bigdecimal b2  = Bigdecimal.valueOf(1298L);

b1 = b1.add(b2);
b1 = b1.subtract(b2);
b1 = b1.multiply(b2);
b1 = b1.divide(b2);
b1 = b1.negete();

No comments:

Post a Comment