There is an input. It is necessary that when the user enters a number, for example, 2.3445, it is automatically replaced by 2.34.

var inp = $('.num'); $('.num').keyup(function () { if (!this.value.match(/^[0-9,.]+$/)) { this.value = this.value.replace(/[^0-9,.]/g, ''); } var val = $('.num').val(); //console.log(val); var numReplace = val.replace(",", "."); var numToFloat = parseFloat(numReplace); var num = numToFloat.toFixed(2); inp.val(num); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class='num' > </input> 

Everything works in the console, but there is no real input. The number is replaced, but then the cursor gets to the end of the line and it is very difficult then to edit it. How to make it possible to change it again without any problems after auto-correcting the number?

  • The counter question is: how should the program understand that the user has finished entering the number? - Zhukov Roman
  • I do not know . that's why he turned here - Kolya Vantukh
  • or maybe just hang up on input change? It turns out that when the user has finished entering, everything is rounded and the comma is replaced ... And the user will not pay attention and you will not need to check the correctness of the input 100 times ... - Geri4

1 answer 1

The problem with your code is that it is unknown when the user completes the input. With high probability we can assume that when he leaves input, he introduced exactly what he wanted.

Therefore, you can replace keyup with blur . After that, if you need to, you can go back and edit the value without problems.

 var inp = $('.num'); $('.num').blur(function () { if (!this.value.match(/^[0-9,.]+$/)) { this.value = this.value.replace(/[^0-9,.]/g, ''); } var val = $('.num').val(); //console.log(val); var numReplace = val.replace(",", "."); var numToFloat = parseFloat(numReplace); var num = numToFloat.toFixed(2); inp.val(num); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class='num' > </input>