Currently I am using following jQuery code to filter only digits:
$('#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(upto to 2 decimal places) like this:
10.2
1.23
1000.10
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 = '';
}
});
try
toFixed(2)
eg:
var number = 2.234239;
var numberfixed=number.toFixed(2);
I think you have to use typing interval, because keyup is to quick and the regex don't 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('');
}
}
You need to change the regular expression used to test the values against.
/^\D+(\.\D\D?)?$/
This will allow numbers with no decimal point, or with a decimal point and one or two digits after.
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 above code fVal is the field value for which you might be checking for.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.