javascript 进行输入以仅获取具有两位小数的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17291517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:46:37  来源:igfitidea点击:

Make input to get only numbers with two decimal places

javascriptjqueryhtmlvalidation

提问by Awan

Currently I am using following jQuery code to filter only digits:

目前我正在使用以下 jQuery 代码来过滤数字:

$('#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:

但我想得到这样的浮点数(最多 2 个小数位):

10.2
1.23
1000.10

回答by Khanh TO

Try this regex:

试试这个正则表达式:

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

Your JS:

你的JS:

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

回答by Shinov T

try

尝试

toFixed(2)

eg:

例如:

var number = 2.234239;
var numberfixed=number.toFixed(2); 

回答by JTC

I think you have to use typing interval, because keyup is to quick and the regex don't approve something like this 0.

我认为你必须使用打字间隔,因为 keyup 太快了,正则表达式不批准这样的事情 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/

http://jsfiddle.net/jWbsE/

回答by knolleary

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.

这将允许没有小数点的数字,或者有一个小数点和一两个数字。

回答by Umang Rustagi

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 fValis the field value for which you might be checking for.

在上面的代码中fVal是您可能要检查的字段值。