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

}
``````

## Comments

1. JIS says:

This post really helped me. Thanks

2. Niraj says:

Hi Pankaj

i have 3 sevrices runing in my project and i wanto to secure my all three services’s jmx on rmi. i am not getting where do i set these key and value i.e means which file.
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.password.file=jmxremote.password

Comments are closed.

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