Java Decimal Rounding to round double

Sometimes while working with double and floats, we need to round them to specific decimal points for calculation. For example, stores round final price to 2 decimal places with half-up rounding mode.

Prior to Java 5, DecimalFormat class was used for rounding purpose but working with it was not in line with numbers and it doesn’t provide many options. So Java 5 introduced RoundingMode enum and BigDecimal class was enhanced to use RoundingMode to get almost any type of rounding you want.

Using BigDecimal with RoundingMode feels like you are working with decimals and it’s very easy to use. Here is a sample program showing it’s usage.

By admin

Leave a Reply

%d bloggers like this: