How to round a number to n decimal places in Java

Posted by Alex Spurling on Stack Overflow See other posts from Stack Overflow or by Alex Spurling
Published on 2008-09-30T16:01:34Z Indexed on 2010/04/22 14:43 UTC
Read the original article Hit count: 143

Filed under:
|
|
|
|

What I'd like is a method to convert a double to a string which rounds using the half-up method. I.e. if the decimal to be rounded is a 5, it always rounds up the previous number. This is the standard method of rounding most people expect in most situations.

I also would like only significant digits to be displayed. That is there should not be any trailing zeroes.

I know one method of doing this is to use the String.format method:

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about decimal