Best way to round number to nth decimal place in Java

To format numbers, Java provides classes like NumberFormat and DecimalFormat classes. DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale. All of these can be localized.

Read more about DecimalFormat class on Oracle website.

For example, if you want to format a decimal number up to 4 decimal places using ceiling, then you can use like below:

DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);
for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {
	Double d = n.doubleValue();
	System.out.println(df.format(d));
}

Output:

12
123.1235
0.23
0.1
2341234.2125

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.