BigDecimal Class in Java

Share and Enjoy !

 BigDecimal Class in Java

BigDecimal Class in Java

BigDecimal supports arbitrary precision  floating point rational numbers.A BigDecimal object provides a great way to represent a real number that exceeds the range or precision that can be represented by double value or the rounding that is done on a double value is acceptable.We can use them for accurate calculations like monetary or financial application .
BigDecimal representation consists of an unlimited precision integer value and an integer scale factor.The scale factor indicates a power of 10 that the integer value is implicitly divided by.
BigDecimal objects are represented as an integer of arbitrary size and an scale that represents the number of decimal places in the given BigDecimal.
BigDecimal is useful when we do comparisons and mathematical operations with other BigDecimal objects.If during operation such a division needs a rounding method,the BigDecimal defines constants to represent the different rounding method.

How BigDecimal is represented?

If the BigDecimal value is represented by 456.7892 then the integer value is 4567892 abd scale factor is 4.
Scale factor can not be negative and BigDecimal number can not overflow.

The structure of the BigDecimal class is given as:

``````public class java.math.BigDecimal extends
java.lang.Number {
//Constructors
public BigDecimal(String val) throws NumberFormatException;
public BigDecimal(double val) throws NumberFormatException;
public BigDecimal(BigInteger val);
public BigDecimal(BigInteger val, int scale) throws
NumberFormatException;
// Constants
public static final int ROUND_CEILING;
public static final int ROUND_DOWN;
public static final int ROUND_FLOOR;
public static final int ROUND_HALF_DOWN;
public static final int ROUND_HALF_EVEN;
public static final int ROUND_HALF_UP;
public static final int ROUND_UNNECESSARY;
public static final int ROUND_UP;
//Methods
public static BigDecimal valueOf(long val, int scale)
throws NumberFormatException;
public BigDecimal abs();
public BigDecimal add(BigDecimal val);
public int compareTo(BigDecimal val);
public BigDecimal divide(BigDecimal val, int scale, int roundingMode) throws
ArithmeticException, IllegalArgumentException;
public BigDecimal divide(BigDecimal val, int roundingMode) throws
ArithmeticException, IllegalArgumentException;
public double doubleValue();
public boolean equals(Object x);
public float floatValue();
public int hashCode();
public int intValue();
public long longValue();
public BigDecimal max(BigDecimal val);
public BigDecimal min(BigDecimal val);
public BigDecimal movePointLeft(int n);
public BigDecimal movePointRight(int n);
public BigDecimal multiply(BigDecimal val);
public BigDecimal negate();
public int scale();
public BigDecimal setScale(int scale, int roundingMode) throws
ArithmeticException, IllegalArgumentException;
public BigDecimal setScale(int scale) throws ArithmeticException,
IllegalArgumentException;
public int signum();
public BigDecimal subtract(BigDecimal val);
public BigInteger toBigInteger();
public String toString();
}``````

`public BigDecimal(String val) throws NumberFormatException;`

Creates a BigDecimal number with the given string specified
in the argument.

The String val construction rule:

• It can have optional minus sign followed by zero and
more decimal digits followed by an optional franction
like(-xyz.mno)
• The fraction must contain a decimal point and zero or
more decimal digits.
• The String must contain at least one digit in the integer
part or fractional part.
• The scale of the BigDecimal is created is equal to the number of the digits to the right of the decimal point or ‘0’ if there is no decimal point.
• The mapping from character to digit is performed by characeter.digit() method.
• If the String can not be parsed to valid BigDecimal,we get the NumberFormatException.
`public BigDecimal(double val) throws NumberFormatException;`

Creates a BigDecimal number with the given value- val.The scale of this number is the smallest value such that 10 to the power scale x value- it represents the integer. If the double value represents Double.NEGATIVE_INFINITY
Double.POSITIVE_INFINITY or Double.NaN NumberFormatException is thrown.

`public BigDecimal(BigInteger val);`

Creates a BigDecimal from BigInteger. The scale of the BigDecimal is zero.(0).

```public BigDecimal(BigInteger val, int scale) throws
NumberFormatException;```

Creates a BigDecimal from BigInteger and Scale. The scale specifies how many digits of the BigInteger fall right of the decimal point. It throws NumberFormatException if the scale is negative.
BigDecimal is zero.(0).

`public static final int ROUND_CEILING;`

A rounding method towards positive infinity.The value is rounded to the least integer greater than equal to its value.
Example 3.5 is rounded to 4 and -3.5 is rounded to -3

`public static final int ROUND_DOWN;`

A rounding method towards zero.This is used during truncation.
Example 3.5 is rounded to 5 and -3.5 is rounded to -3

`public static final int ROUND_FLOOR;`

A rounding method towards negative infinity.The value is rounded to the greater integer less than equal to its value.

Example 3.5 is rounded to 3 and -3.5
is rounded to -4

`public static final int ROUND_HALF_DOWN;`

A rounding method where the digit prior to a discarded fraction if the fraction is greater than .5,otherwise the the digit remains same.
Example- 3.5 rouns to 3,3.51 rounds to 4
-3.5 rounds to -3 and -3.54 rounds to -4

`public static final int ROUND_HALF_EVEN;`

A rounding method that follows if the digit prior to the discarded fraction is odd. Otherwise it follows the ROUND_HALF_DOWN.
Example 2.5 rounds to 2,3.5 rounds to 4
-3.5 rounds to -3 and -3.5 rounds to -4

`public static final int ROUND_HALF_UP;`

A rounding method that increments the digit prior to a discarded fraction if the fraction is greater than or equal to .5,otherwise the digit is unchanged.
Example-3.5 rounds to 4,3.49 rounds to 3
-3.5 rounds to -4 and -3.49 rounds to -3

`public static final int ROUND_UNNECESSARY;`

A constant that signifies that rounding is not necessary.If the result really does require rounding,an ArithmeticException is thrown.

`public static final int ROUND_UP;`

A rounding method that rounds away from zero by truncating.
Example- 3.5 rounds to 4
-3.5 rounds to -4

```public static BigDecimal valueOf(long val, int scale)
throws NumberFormatException;```

Returns the BigDecimal value from the given number long type and scale specified. The scale specifies how many digits falls to the right of the decimal point. If scale is negative(<0) , it throws NumberFormatException.

`public static BigDecimal valueOf(long val);`

Returns the BigDecimal value from the given number long type. The scale created for this number is zero.

`public BigDecimal abs();`

It returns the absolute value of the BigDecimal number.If the BigDecimal number is positive,it is returned as it is. If it is negative,then a new BigDecimal number is returned . The new number contains this BigDecimal number. The scale is same for both new nad old BigDecimal number.

`public BigDecimal add(BigDecimal val);`

Returns the sum of two BigDecimal numbers and put into a
new BigDecimal number.The scale is the maximum of the two
numbers.

`public int compareTo(BigDecimal val);`

This method compares this BigDecimal value to a given BigDecimal value and returns the value indicating the result of the comparison. The two bigDecimals if have same value but different scales are considered as equal.

it can return the followings

• -1 if this number is less that the value of the BigDecimal.
• 0 if the numbers are equal
• 1 if this number is greater than BigDecimal.

This method can be used to compare using standard boolean
comparison operators(==,!=,<=,<,>,>=,>)

```public BigDecimal divide(BigDecimal val, int scale,
int roundingMode) throws ArithmeticException,
IllegalArgumentException;```

This method returns the quotient that results from dividing this BigDecimal number by the given bigDecimal number.It also applies a specified rounding mode.The quitient is returned
as a new BigDecimal Number that has the scale as the scale of this BigDecimal number.One of the rounding constants must be  specified for rounding mode.
Throws ArithmeticException if the BigDecimal is zero(0) or
ROUND_UNNECESSARY is specified for the rounding mode but
rounding is necessary.
Throws IllegalArgumentException if rounding mode is not a
valid value.

`public BigDecimal divide(BigDecimal val, int roundingMode) throws ArithmeticException, IllegalArgumentException;`

This method returns quotient that results from dividing this BigDecimal by the given BigDecimal. It applies the specified rounding mode.

The quotient is returned as a new BigDecimal that has the given scale.One of the rounding constants must be specified for the rounding mode.Throws ArithmeticException is BigDecimal is 0 if the scale is less than zero or if ROUND_UNNECESSARY is specified for the rounding mode but rounding is necessary.It can also throw IllegalArgumentException if rounding mode is not a valid value.

`public double doubleValue();`

This method overrides the Number.doubleValue() and returns the double representation of a BigDecimal number.If the value exceeds the limit of double,double.POSITIVE_INFINITY or double.NEGATIVE_INFINITY is returned.

`public boolean equals(Object x);`

This method overrides Object.equals() method and returns true if x is an instance of BigDecimal and if it represents the same value or that of parameter.It returns false if they are not equal.

`public float floatValue();`

This method overrides the Number.floatValue() and returns the float representation of a BigDecimal number.If the value exceeds the limit of float,float.POSITIVE_INFINITY or float.NEGATIVE_INFINITY is returned.

`public int hashCode();`

This method overrides the Object.hasCode() method and returns a hashcode for this BigDecimal.

`public int intValue();`

This method overrides the Number.intValue() and returns the int representation of a BigDecimal number.If the value exceeds the limit of int ,the high order excessive bits  are discarded and if there is any fractional part of the BigDecimal, it will be truncated.

`public long longValue();`

This method overrides the Number.longValue() and returns the long representation of a BigDecimal number.If the value exceeds the limit of long,the high order excessive bits  are discarded and if there is any fractional part of the BigDecimal, it will be truncated.

`public BigDecimal max(BigDecimal val);`

This metod returns the greater BigDecimal number between this and the given BigDecimal number.

`public BigDecimal min(BigDecimal val);`

This method returns the lesser BigDecimal number between this and the given BigDecimal number.

`public BigDecimal movePointLeft(int n);`

This method returns a BigDecimal that is computed by shifting the decimal point of this BigDecimal by the given number of digits to the left.If n is non negative,the value of the new BigDecimal is
the same as the current value and the scale is increased by n.
if n is negative the method call is same as movePointRight(n).

`public BigDecimal movePointRight(int n);`

This method returns a BigDecimal that is computed by shifting the decimal point of this BigDecimal by the given number of digits to the right.If n is non negative,the value of the new BigDecimal is the same as the current value and the scale is decreased
by n.if n is negative the method call is same as movePointLeft(-n)

`public BigDecimal multiply(BigDecimal val);`

This method multiplies this BigDecimal with the given BigDecimal and returns the new BigDecimal number. The value of the new BigDecimal is the product of the values of two BigDecimal objects added and the scale is sum of their two scales.

`public BigDecimal negate();`

It returns a new BigDecimal that is identical to the BigDecimal except that its sign is reversed.But both the scale is same.

`public int scale();`

It returns the scale of the BigDecimal number.

```public BigDecimal setScale(int scale) throws
ArithmeticException, IllegalArgumentException;```

This method takes the scale as input and creates a new BigDecimal that has the given scale and a value that is calculated by multiplying or dividing the value of this BigDecimal by the appropriate power of 10 to retain the overall value. It is mostly used to increase the scale number ,however if,there are enough zeros in the fractional part of the value to allow for rescaling without loss of precision. It is equivalent to call setScale(int scale,int roundMode) Where roundMode is equal to BigDecimal.ROUND_UNNECESSARY.

```public BigDecimal setScale(int scale, int roundingMode)
throwsArithmeticException, IllegalArgumentException;```

This method creates a new BigDecimal that has the given scale and a value that is calculated by multiplying or dividing the value of this BigDecimal by the appropriate power of 10 to maintain the overall value. When the scale is reduced, the value must be divided, the precision may be lost. In that case the specified rounding mode is used.

If scale is less than zero(i.e negative) or if the ROUND_UNNECESSARY is specified for the rounding mode but the rounding is necessary,ArithmeticException is thrown.

If rounding mode is not a valid value,it can throw IllegalArgumentException.

`public int signum();`
This method returns a value indicating the sign of this BigDecimal number. It returns

• -1 if this number is negative
• 0 if this number is zero
• 1 if this number is positive.

`public BigDecimal subtract(BigDecimal val);`

This method subtract the given BigDecimal from this BigDecimal and returns as a new BigDecimal. The scale is the maximum of their two scales.

`public BigInteger toBigInteger();`

This method returns the value of this BigDecimal as BigInteger. The fractional part (if any) is truncated.

`public String toString();`

This method returns a String representation of this BigDecimal . A minus sign represents the sign and decimal point is used to represent a scale. The mapping from digits to characters is provided by character.forDigit() method.

Other Inherited methods

BigDecimal class also inherits methods from Number and Object class. These methods are:

• byteValue()
• shortValue()
• getClass()
• finalize()
• clone()
• wait()
• wait(long)
• wait(long,int)
• notify()
• notifyAll()