title: Format a number using DecimalFormat in Android
body: <p>I have an EditText and I have set an input filter to only allow numbers which complains this regular expression:</p>
  
  <pre><code>^\\d{1,8}(\\.\\d{0,2})?$
  </code></pre>
  
  <p>that is, 8 integer and 2 fractional digits.</p>
  
  <p>Note that, "0." (1 digit followed by a period) is permitted.</p>
  
  <p>On edittext focus lost, I would like to read the text in the edittext and format it to show numbers grouped and removing not significant digits. For example, some scenarios:</p>
  
  <p>1) if user types 1000. (with period at the end and not followed by digits), I want to display 1,000  in edittext
  2) if user types 000012. or 000012 or 000012.0 or 000012.00 I want to show 12
  3) If user types 1230.90 I want to display 1,230.9</p>
  
  <p>so I perform below, let's say text is the number to be formatted:</p>
  
  <pre><code>                    // Prepare format to apply
                      DecimalFormat format = new DecimalFormat();
                      format.setGroupingUsed(true);
                      format.setMaximumIntegerDigits(8);
                      format.setMaximumFractionDigits(2);
  
                      // Formats the number
                      String formattedText = format.format(text);
  </code></pre>
  
  <p>I know I can do:</p>
  
  <pre><code>DecimalFormat format = new DecimalFormat("########.##");
  </code></pre>
  
  <p>so when applying format using:</p>
  
  <pre><code>String formattedText = format.format(text);
  </code></pre>
  
  <p>It crashes.</p>
  
  <p>For example I have tried to format 0. and 0.5 numbers with no luck.</p>
  
  <p>How to get rid of this?</p>