BigDecimal Class in Java

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.009999999999999998

Input : 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }    
}        

chevron_right


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:

  1. BigDecimal abs​(): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, and whose scale is this.scale().
  2. 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.
  3. BigDecimal add​(BigDecimal augend): This method returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()).
  4. BigDecimal add​(BigDecimal augend, MathContext mc): This method returns a BigDecimal whose value is (this + augend), with rounding according to the context settings.
  5. byte byteValueExact​(): This method converts this BigDecimal to a byte, checking for lost information.
  6. int compareTo​(BigDecimal val): This method compares this BigDecimal with the specified BigDecimal.
  7. 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.
  8. BigDecimal divide​(BigDecimal divisor, int scale, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is as specified.
  9. BigDecimal divide​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this / divisor), with rounding according to the context settings.
  10. BigDecimal divide​(BigDecimal divisor, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is this.scale().
  11. 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.
  12. 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.
  13. BigDecimal divideToIntegralValue​(BigDecimal divisor): This method returns a BigDecimal whose value is the integer part of the quotient (this / divisor) rounded down.
  14. BigDecimal divideToIntegralValue​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is the integer part of (this / divisor).
  15. double doubleValue​(): This method converts this BigDecimal to a double.
  16. boolean equals​(Object x): This method compares this BigDecimal with the specified Object for equality.
  17. float floatValue​(): This method converts this BigDecimal to a float.
  18. int hashCode​(): This method returns the hash code for this BigDecimal.
  19. int intValue​(): This method converts this BigDecimal to an int.
  20. int intValueExact​(): This method converts this BigDecimal to an int, checking for lost information.
  21. long longValue​(): This method converts this BigDecimal to a long.
  22. long longValueExact​(): This method converts this BigDecimal to a long, checking for lost information.
  23. BigDecimal max​(BigDecimal val): This method returns the maximum of this BigDecimal and val.
  24. BigDecimal min​(BigDecimal val): This method returns the minimum of this BigDecimal and val.
  25. 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.
  26. 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.
  27. BigDecimal multiply​(BigDecimal multiplicand): This method returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).
  28. BigDecimal multiply​(BigDecimal multiplicand, MathContext mc): This method returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings.
  29. BigDecimal negate​(): This method returns a BigDecimal whose value is (-this), and whose scale is this.scale().
  30. BigDecimal negate​(MathContext mc): This method returns a BigDecimal whose value is (-this), with rounding according to the context settings.
  31. BigDecimal plus​(): This method returns a BigDecimal whose value is (+this), and whose scale is this.scale().
  32. BigDecimal plus​(MathContext mc): This method returns a BigDecimal whose value is (+this), with rounding according to the context settings.
  33. BigDecimal pow​(int n): This method returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision.
  34. BigDecimal pow​(int n, MathContext mc): This method returns a BigDecimal whose value is (thisn).
  35. int precision​(): This method returns the precision of this BigDecimal.
  36. BigDecimal remainder​(BigDecimal divisor): This method returns a BigDecimal whose value is (this % divisor).
  37. BigDecimal remainder​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this % divisor), with rounding according to the context settings.
  38. BigDecimal round​(MathContext mc): This method returns a BigDecimal rounded according to the MathContext settings.
  39. int scale​(): This method returns the scale of this BigDecimal.
  40. BigDecimal scaleByPowerOfTen​(int n): This method returns a BigDecimal whose numerical value is equal to (this * 10n).
  41. 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.
  42. 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.
  43. short shortValueExact​(): This method converts this BigDecimal to a short, checking for lost information.
  44. int signum​(): This method returns the signum function of this BigDecimal.
  45. BigDecimal sqrt​(MathContext mc): This method returns an approximation to the square root of this with rounding according to the context settings.
  46. BigDecimal stripTrailingZeros​(): This method returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation.
  47. BigDecimal subtract​(BigDecimal subtrahend): This method returns a BigDecimal whose value is (this – subtrahend), and whose scale is max(this.scale(), subtrahend.scale()).
  48. BigDecimal subtract​(BigDecimal subtrahend, MathContext mc): This method returns a BigDecimal whose value is (this – subtrahend), with rounding according to the context settings.
  49. BigInteger toBigInteger​(): This method converts this BigDecimal to a BigInteger.
  50. BigInteger toBigIntegerExact​(): This method converts this BigDecimal to a BigInteger, checking for lost information.
  51. String toEngineeringString​(): This method returns a string representation of this BigDecimal, using engineering notation if an exponent is needed.
  52. String toPlainString​(): This method returns a string representation of this BigDecimal without an exponent field.
  53. String toString​(): This method returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.
  54. BigDecimal ulp​(): This method returns the size of an ulp, a unit in the last place, of this BigDecimal.
  55. BigInteger unscaledValue​(): This method returns a BigInteger whose value is the unscaled value of this BigDecimal.
  56. 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.
  57. static BigDecimal valueOf​(long val): This method translates a long value into a BigDecimal with a scale of zero.
  58. static BigDecimal valueOf​(long unscaledVal, int scale): This method translates a long unscaled value and an int scale into a BigDecimal.

For more examples visit Java BigDecimal Examples

Related Articles:

  • Using BigDecimal in Java to calculate PI number up to 200 decimal digits
  • Make cents with BigDecimal
  • For more functions and details refer Class BigDecimal



    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.