title: How does this code add commas before every three digits?
body: <p>Help me to understand how this code works. It essentially adds commas into a string of numbers. So if the user types a 1 to 3 digit number it is unchanged. For a four digit number ,it adds a comma so</p>
  
  <ul>
  <li>1111 becomes 1,111</li>
  <li>11111 becomes 11,111</li>
  <li>111111111 becomes 11,111,111</li>
  </ul>
  
  <p>and so on. Here's the code:</p>
  
  <pre><code>private String addCommasToNumericString (String digits)
  {
      String result = "";
      int len = digits.length();
      int nDigits = 0;
  
      for (int i = len - 1; i &gt;= 0; i--)                      
      {
          result = digits.charAt(i) + result;                 
          nDigits++;                                          
          if (((nDigits % 3) == 0) &amp;&amp; (i &gt; 0))                
          {
              result = "," + result;
          }
      }
      return (result);
  }
  </code></pre>
  
  <p>I´ll explain what I <em>do</em> understand of it</p>
  
  <p>The <code>for</code> loop basically counts the length of the number the user has written to avoid putting a comma before the first number (e.g. ,1111). And while <code>i</code> is less than the length of the string it subtracts <code>1</code>.</p>
  
  <p><code>result</code> returns the char at position <code>i</code>, since it counts downwards it returns the chars "opposite" from right towards left.</p>
  
  <p><code>nDigits</code> adds 1 from to the initial value of <code>0</code> on each iteration through the loop.</p>
  
  <p>I guess now is where I am having trouble seeing exactly what is going on: <code>if ("nDigits % 3)  == 0</code>.</p>
  
  <p>So for the two first iteration through loop it will not execute the <code>if</code> loop because: </p>
  
  <ul>
  <li>1 % 3 = 1</li>
  <li>2 % 3 = 2</li>
  <li>3 % 3 = 0</li>
  </ul>
  
  <p><code>nDigits</code> starts out as <code>1</code> because of the <code>nDigits++</code> code inside the <code>for</code> loop, so how does it put the comma after three digits and not two? And how does it know when there is only 4 or 5 digits to place the comma corretly at position 1 and two (1,111 - 11,111)?</p>