Name

BigDecimal

Synopsis

This subclass of java.lang.Number represents a floating-point number of arbitrary size and precision. Because it uses a decimal rather than binary floating-point representation, it is not subject to the rounding errors that the float and double types are. This makes BigDecimal well-suited to financial and similar applications.

BigDecimal provides add( ) , subtract( ), multiply( ), and divide( ) methods to support basic arithmetic. In Java 5.0, this class has been expanded to define many more methods, including pow( ) for exponentiation. Many of the new methods use a MathContext to specify the desired precision of the result and the RoundingMode to be used to achieve that precision.

BigDecimal extends Number and implements the Comparable interface. The compareTo( ) method compares the value of two BigDecimal objects and returns -1, 0, or 1 to indicate the result of the comparison. Use this method in place of the <, <=, >, and >= operators that you’d use with float and double values.

A BigDecimal object is represented as an integer of arbitrary size and an integer scale that specifies the number of decimal places in the value. When working with BigDecimal values, you can explicitly specify the precision (i.e., the number of decimal places) you are interested in. Also, whenever a BigDecimal method can discard precision (e.g., in a division operation), you are required to specify what sort of rounding should be performed on the digit to the left of the discarded ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.