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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.journaldev.misc; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; public class RoundingExample { public static void main(String[] args) { double l = 100.34567890; //similar like RegEx but don't have much options DecimalFormat df = new DecimalFormat("#.##"); System.out.println(df.format(l)); //2 decimal places rounding with half up rounding mode System.out.println(BigDecimal.valueOf(l).setScale(2, RoundingMode.HALF_UP)); //3 decimal places rounding with ceiling rounding mode System.out.println(BigDecimal.valueOf(l).setScale(3, RoundingMode.CEILING)); System.out.println(BigDecimal.valueOf(l).setScale(0, RoundingMode.CEILING)); //integer rounding with floor rounding mode System.out.println(BigDecimal.valueOf(l).setScale(0, RoundingMode.FLOOR)); } } |