Skip to content

JavaScript limit input to 2 decimal places | Restrict input example

  • by

Use JavaScript for validation input or use step=".01", which allows up to two decimal places on keypress input.

Here are the test cases:

1.25 – Allowed

12.5 – Allowed

125.5 – Allowed

125.55 – Allowed

123.555 – Not Allowed

Examples of JavaScript limit input to 2 decimal places

HTML example code:-

Example 1: Using JavaScript validation

The input box will not allow a 3rd decimal place. You have also use indexof() and substr() method of JS.

<!DOCTYPE html>
<html>
<head>

    <script>

      var validate = function(e) {
          var t = e.value;
          e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
      }
  </script>
</head>
<body>

    <p> Enter the number</p>
    <input type="text" id="resultText" oninput="validate(this)" />

</body>

Output:

JavaScript limit input to 2 decimal places

Example 2: Using input “step” attribute

The step allows for any number of decimal places, use step=".01", which allows up to two decimal places.

Here is Simple HTML code:-

<!-- wp:paragraph -->
<p>Here is Simple HTML code:-</p>
<!-- /wp:paragraph -->

Output:

Restrict to 2 decimal places in keypress of a text box

Do comment if you have doubts and suggestions on this JS topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *