title: How to format a double with variable amount of decimal digits
body: <p>I was working on a task where I was struck handling a negative scenario mentioned below </p>
  
  <p>If the Value is less than 1 then I want to format (add)   4 decimal points to it .</p>
  
  <p>For example if value is 0.4567 then I need 0.4567</p>
  
  <p>Or else if the value is greater than 1 format with only 2 digits.</p>
  
  <p>For example if value is 444.9 then I need 444.90</p>
  
  <p>Everything above mentioned is working fine, but struck on this below condition </p>
  
  <p>That is if the value is less than 1 and it ends as zeros (0.1000 ,  0.6000) , It makes no sense to print 0.2000, so in that case I want the output to be only as 0.20 </p>
  
  <p>This is my program below </p>
  
  <pre><code>package com;
  import java.text.DecimalFormat;
  public class Test {
      public static void main(String args[]) {
          try {
              String result = "";
              Test test = new Test();
              double value = 444.9;
              if (value &lt; 1) {
                  result = test.numberFormat(value, 4);
              } else {
                  result = test.numberFormat(value, 2);
              }
              System.out.println(result);
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
      public String numberFormat(double d, int decimals) {
          if (2 == decimals)
              return new DecimalFormat("#,###,###,##0.00").format(d);
          else if (0 == decimals)
              return new DecimalFormat("#,###,###,##0").format(d);
          else if (3 == decimals)
              return new DecimalFormat("#,###,###,##0.000").format(d);
          else if (4 == decimals)
              return new DecimalFormat("#,###,###,##0.0000").format(d);
          return String.valueOf(d);
      }
  
  }
  </code></pre>