The BigDecimal class provides operations on double numbers for arithmetic, scale handling, rounding, comparison, format conversion and hashing. It can handle very large and very small floating point numbers with great precision but compensating with the time complexity a bit. A BigDecimal consists of a random precision integer unscaled value and a 32-bit integer scale. If greater than or equal to zero, the scale is the number of digits to the right of the decimal point. If less than zero, the unscaled value of the number is multiplied by 10^(-scale).
Examples:
Input : double a=0.03;
double b=0.04;
double c=b-a;
System.out.println(c);
Output :0.009999999999999998Input : BigDecimal _a = new BigDecimal("0.03");
BigDecimal _b = new BigDecimal("0.04");
BigDecimal _c = _b.subtract(_a);
System.out.println(_c);
Output :0.01
Need Of BigDecimal
- The two java primitive types(double and float) are floating point numbers, which is stored as a binary representation of a fraction and a exponent.
- Other primitive types(except boolean) are fixed-point numbers. Unlike fixed point numbers, floating point numbers will most of the times return an answer with a small error (around 10^-19) This is the reason why we end up with 0.009999999999999998 as the result of 0.04-0.03 in the above example.
But BigDecimal provides us with the exact answer.
// Java Program to illustrate BigDecimal Class
import java.math.BigDecimal;
public class BigDecimalExample
{
public static void main(String[] args)
{
// Create two new BigDecimals
BigDecimal bd1 =
new BigDecimal("124567890.0987654321");
BigDecimal bd2 =
new BigDecimal("987654321.123456789");
// Addition of two BigDecimals
bd1 = bd1.add(bd2);
System.out.println("BigDecimal1 = " + bd1);
// Multiplication of two BigDecimals
bd1 = bd1.multiply(bd2);
System.out.println("BigDecimal1 = " + bd1);
// Subtraction of two BigDecimals
bd1 = bd1.subtract(bd2);
System.out.println("BigDecimal1 = " + bd1);
// Division of two BigDecimals
bd1 = bd1.divide(bd2);
System.out.println("BigDecimal1 = " + bd1);
// BigDecima1 raised to the power of 2
bd1 = bd1.pow(2);
System.out.println("BigDecimal1 = " + bd1);
// Negate value of BigDecimal1
bd1 = bd1.negate();
System.out.println("BigDecimal1 = " + bd1);
}
}
Output:-
BigDecimal1 = 1112222211.2222222211
BigDecimal1 = 1098491072963113850.7436076939614540479
BigDecimal1 = 1098491071975459529.6201509049614540479
BigDecimal1 = 1112222210.2222222211
BigDecimal1 = 1237038244911605079.77528397755061728521
BigDecimal1 = -1237038244911605079.77528397755061728521
Declaration
double a, b;
BigDecimal A, B;
Initialization:
a = 5.4;
b = 2.3;
A = BigDecimal.valueOf(5.4);
B = BigDecimal.valueOf(2.3);
If you are given a String representation of a double number then you can initialize in the following manner:
A = new BigDecimal(â5.4â);
B = new BigDecimal(â1238126387123.1234â);
For ease of initialization BigDecimal class has some pre-defined constants:
A = BigDecimal.ONE;
// Other than this, available constants
// are BigDecimal.ZERO and BigDecimal.TEN
Mathematical operations:
int c = a + b;
BigDecimal C = A.add(B);
Other similar function are subtract() , multiply(), divide(), pow()
But all these functions, except pow() which takes integer as its argument, take BigDecimal as their argument so if we want these operation with decimals or string convert them to BigDecimal before passing them to functions as shown below:
String str = â123456789.123456789â;
BigDecimal C = A.add(new BigBigDecimal(str));
double val = 123456789.123456789;
BigDecimal C = A.add(BigDecimal.valueOf(val));
Extraction of value from BigDecimal:
// value should be in limit of double x
double x = A.doubleValue(); // To get string representation of BigDecimal A
String z = A.toString();
Comparison:
if (a < b) {} // For primitive double
if (A.compareTo(B) < 0) {} // For BigDecimal
Actually compareTo returns -1(less than), 0(Equal), 1(greater than) according to values. For equality we can also use:
if (A.equals(B)) {} // A is equal to B Methods of BigDecimal Class:
- BigDecimal absâ(): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, and whose scale is this.scale().
- BigDecimal absâ(MathContext mc): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, with rounding according to the context settings.
- BigDecimal addâ(BigDecimal augend): This method returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()).
- BigDecimal addâ(BigDecimal augend, MathContext mc): This method returns a BigDecimal whose value is (this + augend), with rounding according to the context settings.
- byte byteValueExactâ(): This method converts this BigDecimal to a byte, checking for lost information.
- int compareToâ(BigDecimal val): This method compares this BigDecimal with the specified BigDecimal.
- BigDecimal divideâ(BigDecimal divisor): This method returns a BigDecimal whose value is (this / divisor), and whose preferred scale is (this.scale() - divisor.scale()); if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.
- BigDecimal divideâ(BigDecimal divisor, int scale, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is as specified.
- BigDecimal divideâ(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this / divisor), with rounding according to the context settings.
- BigDecimal divideâ(BigDecimal divisor, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is this.scale().
- BigDecimal[] divideAndRemainderâ(BigDecimal divisor): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands.
- BigDecimal[] divideAndRemainderâ(BigDecimal divisor, MathContext mc): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands calculated with rounding according to the context settings.
- BigDecimal divideToIntegralValueâ(BigDecimal divisor): This method returns a BigDecimal whose value is the integer part of the quotient (this / divisor) rounded down.
- BigDecimal divideToIntegralValueâ(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is the integer part of (this / divisor).
- double doubleValueâ(): This method converts this BigDecimal to a double.
- boolean equalsâ(Object x): This method compares this BigDecimal with the specified Object for equality.
- float floatValueâ(): This method converts this BigDecimal to a float.
- int hashCodeâ(): This method returns the hash code for this BigDecimal.
- int intValueâ(): This method converts this BigDecimal to an int.
- int intValueExactâ(): This method converts this BigDecimal to an int, checking for lost information.
- long longValueâ(): This method converts this BigDecimal to a long.
- long longValueExactâ(): This method converts this BigDecimal to a long, checking for lost information.
- BigDecimal maxâ(BigDecimal val): This method returns the maximum of this BigDecimal and val.
- BigDecimal minâ(BigDecimal val): This method returns the minimum of this BigDecimal and val.
- BigDecimal movePointLeftâ(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the left.
- BigDecimal movePointRightâ(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the right.
- BigDecimal multiplyâ(BigDecimal multiplicand): This method returns a BigDecimal whose value is (this à multiplicand), and whose scale is (this.scale() + multiplicand.scale()).
- BigDecimal multiplyâ(BigDecimal multiplicand, MathContext mc): This method returns a BigDecimal whose value is (this à multiplicand), with rounding according to the context settings.
- BigDecimal negateâ(): This method returns a BigDecimal whose value is (-this), and whose scale is this.scale().
- BigDecimal negateâ(MathContext mc): This method returns a BigDecimal whose value is (-this), with rounding according to the context settings.
- BigDecimal plusâ(): This method returns a BigDecimal whose value is (+this), and whose scale is this.scale().
- BigDecimal plusâ(MathContext mc): This method returns a BigDecimal whose value is (+this), with rounding according to the context settings.
- BigDecimal powâ(int n): This method returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision.
- BigDecimal powâ(int n, MathContext mc): This method returns a BigDecimal whose value is (thisn).
- int precisionâ(): This method returns the precision of this BigDecimal.
- BigDecimal remainderâ(BigDecimal divisor): This method returns a BigDecimal whose value is (this % divisor).
- BigDecimal remainderâ(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this % divisor), with rounding according to the context settings.
- BigDecimal roundâ(MathContext mc): This method returns a BigDecimal rounded according to the MathContext settings.
- int scaleâ(): This method returns the scale of this BigDecimal.
- BigDecimal scaleByPowerOfTenâ(int n): This method returns a BigDecimal whose numerical value is equal to (this * 10n).
- BigDecimal setScaleâ(int newScale): This method returns a BigDecimal whose scale is the specified value, and whose value is numerically equal to this BigDecimal's.
- BigDecimal setScaleâ(int newScale, RoundingMode roundingMode): This method returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal's unscaled value by the appropriate power of ten to maintain its overall value.
- short shortValueExactâ(): This method converts this BigDecimal to a short, checking for lost information.
- int signumâ(): This method returns the signum function of this BigDecimal.
- BigDecimal sqrtâ(MathContext mc): This method returns an approximation to the square root of this with rounding according to the context settings.
- BigDecimal stripTrailingZerosâ(): This method returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation.
- BigDecimal subtractâ(BigDecimal subtrahend): This method returns a BigDecimal whose value is (this - subtrahend), and whose scale is max(this.scale(), subtrahend.scale()).
- BigDecimal subtractâ(BigDecimal subtrahend, MathContext mc): This method returns a BigDecimal whose value is (this - subtrahend), with rounding according to the context settings.
- BigInteger toBigIntegerâ(): This method converts this BigDecimal to a BigInteger.
- BigInteger toBigIntegerExactâ(): This method converts this BigDecimal to a BigInteger, checking for lost information.
- String toEngineeringStringâ(): This method returns a string representation of this BigDecimal, using engineering notation if an exponent is needed.
- String toPlainStringâ(): This method returns a string representation of this BigDecimal without an exponent field.
- String toStringâ(): This method returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.
- BigDecimal ulpâ(): This method returns the size of an ulp, a unit in the last place, of this BigDecimal.
- BigInteger unscaledValueâ(): This method returns a BigInteger whose value is the unscaled value of this BigDecimal.
- static BigDecimal valueOfâ(double val): This method translates a double into a BigDecimal, using the double's canonical string representation provided by the Double.toString(double) method.
- static BigDecimal valueOfâ(long val): This method translates a long value into a BigDecimal with a scale of zero.
- static BigDecimal valueOfâ(long unscaledVal, int scale): This method translates a long unscaled value and an int scale into a BigDecimal.