Explain Codes LogoExplain Codes Logo

Rounding BigDecimal to always have two decimal places

java
decimal-places
bigdecimal-rounding
java-precision-control
Nikita BarsukovbyNikita Barsukov·Aug 25, 2024
TLDR

You can round a BigDecimal to two decimal places using setScale(2, RoundingMode.HALF_UP). This function ensures precision up to two decimal points, rounding up from .005.

// it's as simple as one, two, three...well, almost. BigDecimal rounded = new BigDecimal("123.456").setScale(2, RoundingMode.HALF_UP);

After rounding, rounded becomes 123.46.

But if you want to always round up, regardless of the decimal, use RoundingMode.CEILING:

// When in doubt, round up! BigDecimal roundedUp = new BigDecimal("123.451").setScale(2, RoundingMode.CEILING);

Now, roundedUp equals 123.46, CEILING ensure the value always rounds up.

Tactics for BigDecimal rounding

When playing around with BigDecimal rounding, you can choose from multiple strategies based on your needs.

Half-Up Rounding with setScale

The HALF_UP rounding mode is widely used, and it works just like the round-off method you learned and maybe forgotten in school!

Upward rounding using RoundingMode.CEILING

In scenarios where you want to always round up, choose CEILING. This strategy is particularly useful in financial calculations, where undercharging might cost you a lucrative deal!

Mind the significant digits

The number of significant digits in the BigDecimal comes into play when rounding. For a large number of significant digits, rounding can create quite a difference. So, mind the digits!

Dare to look beyond

Sometimes, native Java methods might not do the trick. In such cases, take refuge in third-party libraries or classes that offer better precision control.

Advanced BigDecimal rounding

Unpredictable scales? No problem!

Dealing with values that have a varying number of decimal points? Keep calm and use the setScale method to standardize them to two decimal points. This will ensure consistency in your numeric formats across the application.

Zero-padding

Need to show two decimals at all times? BigDecimal has got you covered with automatic zero-padding:

// Want two decimal places? You've got it! BigDecimal exactTwo = new BigDecimal("123").setScale(2, RoundingMode.HALF_UP);

In the above example, exactTwo will display as 123.00, fulfilling the two decimal places requirement.

Underflow and overflow handling

Beware of underflow or overflow while performing arithmetic operations with large scale BigDecimal values. Always implement overflow and underflow checks to prevent ArithmeticException or data loss.