Java Decimal Rounding to round double, float to “n” decimal points and different rounding mode

Filed Under: Java

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.


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));
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages