Limit the number of characters in javascript decimal places


The user can enter values ​​into an input text. The thing is, I want to limit the number of characters after the period. Valid example:



That is, the user cannot enter more than three decimal places. Every time a character is inserted, I have to validate this situation. When this situation happens, the input doesn't let you write any more decimal places.


I think you can use something like this:

var input = document.querySelector('input');
var oldVal = '';
input.addEventListener('keyup', function(){
    var parts = this.value.split('.');
    if (parts && parts[1] && parts[1].length > 3) this.value = oldVal;
    oldVal = this.value;

The idea is to break the string by . and knowing the length (length) of the part after the point. If it is greater than 3, then replace the value with the old one.


Scroll to Top