Core Java

BigInteger and BigDecimal In Java

Introduction:

In this quick guide, we’ll introduce you to BigInteger and BigDecimal classes in Java.

BigInteger:

java.math.BigInteger is an immutable class which is used when we need to store and operate on very large integer values.

Consider writing a program involving typical mathematical calculations which probably might end up with a very large integral outcome. For such cases, we must choose to work with BigInteger to avoid data overflow issues.

Instantiation & Basic Usage:

One of the common ways to instantiate a BigInteger would make use of below constructor:

new BigInteger(String value)

Let’s look at some common usages with an example:

BigInteger b1 = new BigInteger("34353646766666667");
BigInteger b2 = new BigInteger("4363775485686776070780607080");

//Common Operations

BigInteger b3 = null;

b3 = b1.add(b2);
b3 = b2.subtract(b1);
b3 = b1.multiply(b2);
b3 = b2.divide(b1);
b3 = b1.gcd(b2);
b3 = b1.power(10); //Note that pow accepts an integer argument

To avoid the outcome being lost, we have assigned it to another variable b3.

Please refer the JavaDoc in case you wish to explore it further.

BigDecimal:

java.math.BigDecimal class is also an immutable class used to store and work with very large decimal numbers,  the ones which can’t fit in basic primitive options available.

Instantiation & Basic Usage:

Common constructors that we are most likely to use includes:

BigDecimal(String value)
BigDecimal(String value, MathContext mc)

BigDecimal(double value)
BigDecimal(double value, MathContext mc)

We need to keep two things in mind while working with decimals:

  1. Precision: number of digits in a number.
  2. Scale: number of digits to the right side of a decimal point in a number.

So for number = 3456.34, precision = 6 and scale = 2.

java.math.MathContext  helps us define precision and RoundingMode to be used to maintain that precision.

Basic Operations:

Let’s look at some basic operations this class supports with the help of an example:

BigDecimal d1 = new BigDecimal(34346364.55);
BigDecimal d2 = new BigDecimal(3534646.4336);

BigDecimal d3 = null;

d3 = d1.add(d2);
d3 = d1.subtract(d2);
d3 = d1.multiply(d2);
d3 = d1.divide(d2, 2, RoundingMode.CEILING); // here, scale = 2
d3 = d1.divide(d2, 2, RoundingMode.FLOOR);

We’ll suggest you exploring other methods of this class by referring to its JavaDoc.

Conclusion:

This was a very short guide introducing us to BigInteger and BigDecimal classes in Java.  We might find them helpful when dealing with large numbers.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *