title: Restrict to 2 decimal places in keypress of a text box?
body: <p>I want to enter a decimal point in a text box. I want to restrict the user by entering more than 2 digits after the decimal point. I have written the code for achieving that in the Keypress event.</p>
  
  <pre><code>function validateFloatKeyPress(el, evt) {
      var charCode = (evt.which) ? evt.which : event.keyCode;
  
      if (charCode != 46 &amp;&amp; charCode &gt; 31 &amp;&amp; (charCode &lt; 48 || charCode &gt; 57)) {
          return false;
      }
  
      if (charCode == 46 &amp;&amp; el.value.indexOf(".") !== -1) {
          return false;
      }
  
      if (el.value.indexOf(".") !== -1)
      {
          var range = document.selection.createRange();
  
          if (range.text != ""){
          }
          else
          {
              var number = el.value.split('.');
              if (number.length == 2 &amp;&amp; number[1].length &gt; 1)
                  return false;
          }
      }
  
      return true;
  }
  &lt;asp:TextBox ID="txtTeamSizeCount" runat="server" onkeypress="return validateFloatKeyPress(this,event);" Width="100px" MaxLength="6"&gt;&lt;/asp:TextBox&gt;
  </code></pre>
  
  <p>The code is working but the issue is: if I enter <b>".75"</b> and then change it to <b>"1.75"</b>, it is not possible. Only way to do it is delete it completely and then type <b>"1.75"</b>. This issue occurs if there are already 2 digits after decimal in the textbox. The conditions that I impose are</p>
  
  <p>a) After decimal is present, it must at least have 1 or 2 digits. For ex <b>.75 or .7 or 10.75 or 333.55 or 333.2</b> is accepted. but not <b>.753 or 12.3335</b></p>
  
  <p><br/>b) Before the decimal, it not a must for the user to enter a value. User must also be able to enter integer numbers also.</p>
  
  <p>Can you tell me what could be the issue?</p>
  
  <p>Thanks,<br/>
  Jollyguy   </p>