Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to round a number to n decimal places in Java

What I might want is a technique to change a twofold over to a string that gathers utilizing the half-together strategy - for example on the off chance that the decimal to be adjusted is 5, it generally gathers together to the following number. This is the standard technique for adjusting the vast majority expect as a rule.

I additionally might want just huge digits to be shown - for example, there ought not to be any following zeroes.

I know one strategy for doing this is to utilize the String. format technique:

String.format("%.5g%n", 0.912385);


returns:
0.91239


which is great, however, it always displays numbers with 5 decimal places even if they are not significant:

String.format("%.5g%n", 0.912300);


returns:

0.91230


Another method is to use the DecimalFormatter:

DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);


returns:

0.91238

However, as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this:

*0.912385 -> 0.91239
0.912300 -> 0.9123


What is the best way to achieve this in Java?
by

2 Answers

espadacoder11
Use setRoundingMode, set the RoundingMode explicitly to handle your issue with the half-even round, then use the format pattern for your required output.

Example:

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

gives the output:

12
123.1235
0.23
0.1
2341234.2125
kshitijrana14
Assuming value is a double, you can do:
(double)Math.round(value * 100000d) / 100000d

That's for 5 digits precision. The number of zeros indicate the number of decimals.

Login / Signup to Answer the Question.