How to Allow Only 3 Digits After Decimal Using JavaScript
In this article, we will explore two methods to restrict input to only three digits after the decimal point using JavaScript.
Whether you're working on a financial application or a data entry form, limiting the number of decimal places can help maintain data accuracy and consistency.
Using Regular Expressions
Regular expressions (regex) offer a powerful way to validate and manipulate input. Here's how you can use regex to allow only three digits after the decimal point.
<input type="text" id="decimalInput"> <script> document.getElementById('decimalInput').addEventListener('input', function () { this.value = this.value.replace(/(\.\d{3})\d+$/, '$1'); }); </script>
Explanation:
- We use the addEventListener method to listen for input changes on the input field.
- The regex pattern /(\.\d{3})\d+$/ matches any decimal point followed by three digits and additional digits after that.
- The replace() method is used to replace the matched pattern with the first three digits after the decimal point, effectively limiting the input to three decimal places.
Using JavaScript's toFixed Method
JavaScript's toFixed() method can be used to round a number to a specified number of decimal places.
<input type="text" id="decimalInput"> <script> document.getElementById('decimalInput').addEventListener('input', function () { let value = parseFloat(this.value); if (!isNaN(value)) { this.value = value.toFixed(3); } }); </script>
Explanation:
- We again use addEventListener to listen for input changes.
- parseFloat is used to convert the input value to a floating-point number.
- We check if the conversion is successful (not NaN), and if so, use toFixed(3) to round the number to three decimal places.
- This method ensures that only three decimal places are displayed in the input field.
Conclusion:
In this article, we explored two methods to allow only three digits after the decimal point using JavaScript.
Regular expressions provide a flexible way to enforce this rule, while JavaScript's toFixed() method simplifies the process by rounding the input to the desired precision.