Explain Codes LogoExplain Codes Logo

Bigdecimal setScale and round

java
prompt-engineering
rounding-mode
mathcontext
Nikita BarsukovbyNikita Barsukov·Jan 30, 2025
TLDR

Employ BigDecimal.setScale(int newScale, RoundingMode roundingMode) to establish precision and set defined rounding behavior concurrently. Let's consider a 2 decimal places example with common rounding:

BigDecimal result = new BigDecimal("2.345").setScale(2, RoundingMode.HALF_UP);

Confirms result to 2.35, rounding the third decimal. Opt for a fitting RoundingMode, like HALF_EVEN for bankers' rounding or DOWN for sheer truncation.

Methods explored: setScale or round?

Working with BigDecimal numbers, the decision to use setScale or round can be critical for ensuring calculated precision and desired format. Defining scale indicates number of digits right of the decimal point whilst precision relates to the whole digit count.

setScale provides authority over decimal representation, shaping number of decimal places required, combining setScale and RoundingMode permits trimming or rounding of surplus digits.

Conversely, round molds the number to a specified precision level via a MathContext object, accounting for scale and precision of BigDecimal. The round method may affect both scale and precision depending on the MathContext applied.

Both functions require rounding procedures for non-exact results, making them vital for tasks necessitating precise calculations, like financial applications.

Breakdown: RoundingMode options

Understanding these modes is crucial to manipulating numbers accurately, they will assist with rounding BigDecimal to avoid lengthy decimals or adhere to specific financial rounding standards:

  1. RoundingMode.UP - Away from zero, taking the highway to the danger zone!
  2. RoundingMode.DOWN - Going towards zero, truncating in case of doubt.
  3. RoundingMode.CEILING - Always looking up, rounds towards positive infinity.
  4. RoundingMode.FLOOR - Down to earth, rounds to negative infinity.
  5. RoundingMode.HALF_UP - Round up if in doubt, if equidistant.
  6. RoundingMode.HALF_DOWN - Playing safe, rounds down if unsure.
  7. RoundingMode.HALF_EVEN - Playing even safer, rounds to nearest even neighbour.
  8. RoundingMode.UNNECESSARY - All or nothing, asserts exactness in operation, no rounding needed.

Understanding the terms of the game: precision vs. scale

When handling BigDecimal, understanding the distinction between precision and scale is crucial:

  • Precision - Total count of significant digits ⬅️ and ➡️ of the decimal point.
  • Scale - Count of digits ➡️ of the decimal point.

Precision's impact

Observe how precision impacts calculations using round:

MathContext mc = new MathContext(2, RoundingMode.HALF_UP); BigDecimal number = new BigDecimal("123.456"); BigDecimal result = number.round(mc); // Result is 120 (precision 2 like a precision-guided missile!)

120 as the result highlights how precision governs digit length on both sides of the decimal.

Effect of Scale

Conversely, note how adjusting the scale affects number:

BigDecimal number = new BigDecimal("123.456"); BigDecimal result = number.setScale(1, RoundingMode.HALF_UP); // Result is 123.5 (setScale: the tailor for your BigDecimal suit)

The result is 123.5, showing how only the decimal's right side is changed by adjusting digits count.

Practical application of setScale and round

Managing currency

When handling currency calculations in the big financial world:

BigDecimal payment = new BigDecimal("123.656"); BigDecimal roundedPayment = payment.setScale(2, RoundingMode.HALF_EVEN); // Banker's choice of rounding

Operating tax calculations

For tax computations where every cent counts:

BigDecimal taxRate = new BigDecimal("0.0875"); BigDecimal price = new BigDecimal("9.99"); BigDecimal tax = price.multiply(taxRate).setScale(2, RoundingMode.HALF_UP); // Because who likes extra long receipts?

Catering to international rounding rules

Adapting to varied rounding standards around the world:

BigDecimal value = new BigDecimal("7.5"); BigDecimal roundedForSwedish = value.setScale(0, RoundingMode.HALF_EVEN); // When in Sweden, do as the Swedes do