Enter to get only two decimal places

I am currently using the following jQuery code to filter only numbers:

$('#input_field').keyup(function(e) { if (/\D/g.test(this.value)) { this.value = this.value.replace(/\D/g, ''); } }); 

But I want to get floating point numbers (up to two decimal places) as follows:

 10.2 1.23 1000.10 
+4
source share
5 answers

Try this regex:

 /^\d+(\.\d{0,2})?$/ 

Your js:

 $('#input_field').keyup(function(e) { var regex = /^\d+(\.\d{0,2})?$/g; if (!regex.test(this.value)) { this.value = ''; } }); 
+8
source

try

 toFixed(2) 

eg:

 var number = 2.234239; var numberfixed=number.toFixed(2); 
+3
source

I think you need to use an input interval because keyup is fast and the regex does not approve something like this 0.

 var typingTimer; var doneTypingInterval = 1000; $('.myInputField').keyup(function(){ clearTimeout(typingTimer); if ($('.myInputField').val) { typingTimer = setTimeout(doneTyping, doneTypingInterval); } }); function doneTyping () { var vale = $('.myInputField').val(); var regexTest = /^\d+(?:\.\d\d?)?$/; var ok = regexTest.test(vale); if(!ok){ $('.myInputField').val(''); } } 

http://jsfiddle.net/jWbsE/

+2
source

You need to change the regular expression used to validate the values.

 /^\D+(\.\D\D?)?$/ 

This will allow numbers without a decimal point or with a decimal point and one or two digits after.

+1
source
 var dot = fVal.split("."); var len0 = 0; var len1 = 0; if (dot.length == 2) { len0 = dot[0].length; len1 = dot[1].length; } else if (dot.length > 2) len1 = 3; else len1 = 0; var fValFlt = parseFloat(fVal); var fValN = isNaN(fVal); if ((len1 > 2) || fValN == true || fValFlt < 0) { //failure arguments } else { //success arguments } 

In the above code, fVal is the value of the field for which you can check.

0
source

Source: https://habr.com/ru/post/1488016/


All Articles