Rounding BigDecimal Values
In addition to precise calculations, BigDecimal
also gives you control over how values are rounded—by default all calculations are exact and no rounding occurs. If you do not specify how to round BigDecimal
values and a given value cannot be represented exactly—such as the result of 1 divided by 3, which is 0.3333333...—an ArithmeticException
occurs.
Though we do not do so in this example, you can specify the rounding mode for BigDecimal
by supplying a MathContext
object (package java.math
) to class BigDecimal
’s constructor when you create a BigDecimal
. You may also provide a MathContext
to various BigDecimal
methods that perform calculations. Class MathContext
contains several pre-configured MathContext
objects that ...
Get Java™ How To Program (Early Objects), Tenth 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.