Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 › #HowTo #Html

textbox accept only numbers and 2 digits after decimal point using javascript

In this article, we'll explore a common JavaScript task: limiting input to just two digits after the decimal point using regular expressions (regex).

Whether you're building a form for financial data or simply need to ensure data accuracy, this technique can be incredibly useful.

Input Validation with JavaScript Regex

<input type="text" id="decimalInput" oninput="limitToTwoDecimalPlaces(this)">
<script>
 function limitToTwoDecimalPlaces(inputElement) {
  const regex = /^\d+(\.\d{0,2})?$/;
  const value = inputElement.value;
  
  if (!regex.test(value)) {
    inputElement.value = value.slice(0, -1);
  }
 }
</script>
  1. We use the oninput event to trigger the function whenever the user inputs text.
  2. The regular expression /^\d+(\.\d{0,2})?$/ ensures that the input consists of digits followed by an optional decimal point and up to two decimal digits.
  3. If the input doesn't match the regex, we remove the last character to enforce the two-decimal limit.

JavaScript for Formatting Numbers

<input type="text" id="decimalInput" oninput="formatDecimalInput(this)">
<script>
 function formatDecimalInput(inputElement) {
  const value = inputElement.value;
  const parts = value.split('.');
  if (parts[1] && parts[1].length > 2) {
    parts[1] = parts[1].slice(0, 2);
  }
  inputElement.value = parts.join('.');
}
</script>
  1. This approach doesn't restrict the input but formats it to display only two decimal places.
  2. We split the input value into its integer and decimal parts, and if the decimal part has more than two digits, we keep only the first two.

Conclusion:

In this article, you've learned two methods for allowing only two digits after the decimal point using JavaScript.

The first method uses regex for input validation, while the second method formats the input to display two decimal places.

save
listen
AI Answer
Write Your Answer
loading
back
View All