Skip to main content
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

How to round a number to n decimal places in Java

What I would 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 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations.

I also would like only significant digits to be displayed - i.e. 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?

Answer*

Cancel
2
  • Any reason why Double.valueOf() was chosen over Double.parseDouble()? The valueOf() method returns a Double object, while parseDouble() will return a double primitive. With the way the current code is written, you also apply auto-unboxing to the return to cast it to the primitive that your twoDouble variable expects, an extra bytecode operation. I'd change the answer to use parseDouble() instead.
    ecbrodie
    –  ecbrodie
    2015-12-03 06:25:05 +00:00
    Commented Dec 3, 2015 at 6:25
  • Double.parseDouble() needs String input.
    Ryde
    –  Ryde
    2016-05-05 23:40:46 +00:00
    Commented May 5, 2016 at 23:40

Morty Proxy This is a proxified and sanitized view of the page, visit original site.