title: How to round a number to n decimal places in Java
body: <p>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.</p>
  
  <p>I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes.</p>
  
  <p>I know one method of doing this is to use the <code>String.format</code> method:</p>
  
  <pre><code>String.format("%.5g%n", 0.912385);
  </code></pre>
  
  <p>returns:</p>
  
  <pre><code>0.91239
  </code></pre>
  
  <p>which is great, however it always displays numbers with 5 decimal places even if they are not significant: </p>
  
  <pre><code>String.format("%.5g%n", 0.912300);
  </code></pre>
  
  <p>returns:</p>
  
  <pre><code>0.91230
  </code></pre>
  
  <p>Another method is to use the <code>DecimalFormatter</code>:</p>
  
  <pre><code>DecimalFormat df = new DecimalFormat("#.#####");
  df.format(0.912385);
  </code></pre>
  
  <p>returns:</p>
  
  <pre><code>0.91238
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>0.912385 -&gt; 0.91239
  0.912300 -&gt; 0.9123
  </code></pre>
  
  <p>What is the best way to achieve this in Java?</p>