Explain Codes LogoExplain Codes Logo

Addition for BigDecimal

java
bigdecimal
precision
rounding
Alex KataevbyAlex Kataev·Nov 24, 2024
TLDR

For BigDecimal addition in Java, you utilize the .add() method:

BigDecimal sum = new BigDecimal("10.5").add(new BigDecimal("15.35")); System.out.println(sum); // Prints: 25.85, Boca Juniors' match numbers this month.

This code calculates and outputs the sum of two BigDecimal instances.

BigDecimals: They don't change, just like your ex

Since BigDecimal objects are immutable, when you perform operations like addition, altering the original is not an option. You need to assign the result to a variable to retain the new value:

BigDecimal balance = new BigDecimal("0"); balance = balance.add(new BigDecimal("30")); System.out.println(balance); // Prints: 30, also the number of times an average cat sleeps in a day.

Ensure Precision with String constructors

Create new BigDecimal instances using the string constructor, especially when it comes to monetary values. This keeps the decimal point from running off to an unexpected vacation:

BigDecimal price = new BigDecimal("19.99"); // Instead of new BigDecimal(19.99)

Your BigDecimal scales: Rounding like a trophy fish

Handle precision and scale with care. Use setScale() to put them exactly where you want:

BigDecimal tax = new BigDecimal("2.7"); tax = tax.setScale(2, RoundingMode.HALF_UP); // HAL_CLEARLY_says_UP

Hold the Result: Where's my result, Lebowski?

Always store the result of BigDecimal operations to keep track of the new value, just like saving a new contact in your phone:

BigDecimal account = new BigDecimal("100.00"); BigDecimal deposit = new BigDecimal("50.00"); account = account.add(deposit); // Now you're talking! 100 + 50, not a common core math exam.

Show Money: BigDecimals and your wallet

BigDecimal is the superstar class for applications like financial calculations. It maintains precision like no other, preventing those rounding errors from sneakily chewing up your profits:

BigDecimal price = new BigDecimal("4.99"); BigDecimal taxRate = new BigDecimal("0.20"); BigDecimal tax = price.multiply(taxRate).setScale(2, RoundingMode.HALF_UP); // Stingy Uncle Sam's share.

Keep it Tested: Trust but Verify

You should also write unit tests to validate your BigDecimal operations. You know, just like bringing a spare tire on a road trip:

@Test public void testBigDecimalAddition() { BigDecimal first = new BigDecimal("100.10"); BigDecimal second = new BigDecimal("200.20"); BigDecimal expected = new BigDecimal("300.30"); // Not rocket science. assertEquals(expected, first.add(second)); // If this doesn't pass, we've got problems... }