CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Data

Data
BigDecimal class

The BigDecimal class

java.math.BigDecimal
  • The BigDecimal class provides a way to perform accurate decimal calculations in Java. It also provides a way to store numbers with more than 16 significant digits.
  • You can pass a BigDecimal object to the format method of a NumberFormat object, but NumberFormat objects limit the results to 16 significant digits.

Constructors of the BigDecimal class

Constructor Description
BigDecimal(int) Creates a new BigDecimal object with the specified int value.
BigDecimal(double) Creates a new BigDecimal object with the specified double value.
BigDecimal(long) Creates a new BigDecimal object with the specified long value.
BigDecimal(String) Creates a new BigDecimal object with the specified String object.

Methods of the BigDecimal class

Methods Description
add(value) Returns the value of this BigDecimal object after the specified BigDecimal value has been added to it.
compareTo(value) Compares the value of the BigDecimal object with the value of the specified BigDecimal object and returns -1 if less, 0 if equal, and 1 if greater.
divide(value, scale, rounding-mode) Returns the value of this BigDecimal object divided by the value of the specified BigDecimal object, sets the specified scale, and uses the specified rounding mode.
multiply(value) Returns the value of this BigDecimal object multiplied by the specified BigDecimal value.
setScale(scale, rounding-mode) Sets the scale and rounding mode for the BigDecimal object.
subtract(value) Returns the value of this BigDecimal object after the specified BigDecimal value has been subtracted from it.
toString() Converts the BigDecimal value to a string.

The RoundingMode enumeration

java.math.RoundingMode

Two of the values in the RoundingMode enumeration

Values Description
HALF_UP Round towards the "nearest neighbor" unless both neighbors are equidistant, in which case round up.
HALF_EVEN Round towards the "nearest neighbor" unless both neighbors are equidistant, in which case round toward the even neighbor.

The import statement that's required for BigDecimal arithmetic

import java.math.*; // imports all classes and enumerations in java.math

How to create a BigDecimal object from another BigDecimal object

BigDecimal total2 = new BigDecimal(total.toString());
Previous | BigDecimal class | Use BigDecimal