title: I want to dynamically insert a comma into UITextField for ios Swift3
body: <p>Attempt to change the character of UITextField using NumberFormat failed.</p>
  
  <p>Number: 1000000.00</p>
  
  <p>Result:</p>
  
  <ul>
  <li>1.00</li>
  <li>1,0.00</li>
  <li>10,0.00</li>
  <li>100,0.00</li>
  <li>1,000,0.00</li>
  <li>100,000,0.00</li>
  <li>1,000,000,0.00
         </li>
  </ul>
  
  <p>How can I convert?</p>
  
  <p>Here is my code that failed.</p>
  
  <pre><code>public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -&gt; Bool {
  
  if ((string == "0" || string == "") &amp;&amp; (textField.text! as NSString).range(of: ".").location &lt; range.location) {
      return true
  }
  
  let cs = NSCharacterSet(charactersIn: "0123456789.").inverted
  let filtered = string.components(separatedBy: cs)
  let component = filtered.joined(separator: "")
  let isNumeric = string == component
  
  if isNumeric {
      let formatter = NumberFormatter()
      formatter.numberStyle = .decimal
      formatter.maximumFractionDigits = 0
  
      let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
      let numberWithOutCommas = newString.replacingOccurrences(of: ",", with: "")
      let number = formatter.number(from: numberWithOutCommas)
      if number != nil {
          var formattedString = formatter.string(from: number!)
  
          if string == "." &amp;&amp; range.location == textField.text?.characters.count {
              formattedString = formattedString?.appending(".")
          }
  
          /* // Fail...
          if length! &gt; 1 { 
              formattedString?.insert(",", at: (formattedString?.index((formattedString?.endIndex)!, offsetBy: -1))!) 
          }
          */
  
          textField.text = formattedString
      } else {
          textField.text = nil
      }
  }
  return false
  </code></pre>
  
  <p>}</p>