javascript 只允许输入 2 位小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17916593/
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 10:05:46  来源:igfitidea点击:

Allow to enter only 2 decimal points number

javascript

提问by nebula

I have a condition to allow user to input only 2 decimal points number and restrict the alphabets and other characters. I used the following function:

我有一个条件,允许用户只输入 2 个小数点数字并限制字母和其他字符。我使用了以下功能:

function isNumberKeyOnlyWithDecimalFormat(event,value,id){
        var val = value;
         if (event.shiftKey === true) {
                event.preventDefault();
        }
        if ((event.keyCode >= 48 && event.keyCode <= 57) ||
           (event.keyCode >= 96 && event.keyCode <= 105) ||
            event.keyCode == 8 || 
            event.keyCode == 9 ||  
            event.keyCode == 37 || 
            event.keyCode == 39 || 
            event.keyCode == 46 || 
            event.keyCode == 190) {

        } else {
            event.preventDefault();
        }
        if(val.indexOf('.') !== -1 && event.keyCode == 190){
            event.preventDefault();
        }
        if ((pointPos =   $('#'+id).val().indexOf('.')) >= 0){
            $('#'+id).attr("maxLength", pointPos+3);
        }
        else
            $('#'+id).removeAttr("maxLength");  
        }

It is working fine while first time adding. But it restricts the if i want to edit the digits if it has already 2 decimal place. Can anyone help with this?

第一次添加时它工作正常。但它限制了如果我想编辑数字,如果它已经有 2 个小数位。有人能帮忙吗?

回答by Samer

Try this. It will check the value each time the focus is gone from the input field, but you can use any event you like. It will parse the value as a float, and then round it to 2 decimal points.

试试这个。每次焦点离开输入字段时,它都会检查值,但您可以使用任何您喜欢的事件。它会将值解析为浮点数,然后将其四舍五入到 2 个小数点。

Here is the fiddle: http://jsfiddle.net/sAp9D/

这是小提琴:http: //jsfiddle.net/sAp9D/

HTML:

HTML:

<input type="text" id="the_id" />

JavaScript:

JavaScript:

var input_field = document.getElementById('the_id');

input_field.addEventListener('change', function() {
    var v = parseFloat(this.value);
    if (isNaN(v)) {
        this.value = '';
    } else {
        this.value = v.toFixed(2);
    }
});

回答by Aamir Mahmood

I use the following

我使用以下

// This function will only allow digits
function numericFormat( fld , e , extraStrCheck )
{
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
if ( extraStrCheck )
    strCheck += extraStrCheck;
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;

if (whichCode == 13) return true;  // Enter
if (whichCode == 8) return true;  // Backspace
if (whichCode == 0) return true;  // Null
if (whichCode == 9) return true;  // Tab

key = String.fromCharCode(whichCode);  // Get key value from key code
if ( strCheck.indexOf(key) == -1 ) return false;  // Not a valid key
var x = new String(fld.value);
if ( key == '.' )
{
    var exp = /\./;
    var a = x.search(exp);
    if ( a != -1 ) return false;
}


}

// samer code on change  or on blur event
function allow2decimal(obj){
    var v = parseFloat($(obj).val());



        if (isNaN(v)) {
            $(obj).value = '';
        } else {
            newVal = v.toFixed(2);
            if(newVal >= 100){
                $(obj).val( 100 );
            }else{
                $(obj).val(newVal);
            }

        }

}
//usage
  <input
        onkeypress="return numericFormat( this , event , '.');"
        onchange="allow2decimal(this)"
        value="0.1"
        id="factory_silk" name="factory_silk" />

回答by Hrushi

<html>
    <head>
        <script type="text/javascript">  
        function NumAndTwoDecimals(e, field) {  
        var val = field.value;  
        var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;  
        var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;  
        if (re.test(val)) {  

        }  
        else {  
        val = re1.exec(val);  
        if (val) {  
        field.value = val[0];  
        }  
        else {  
        field.value = "";  
        }  
        }  
        }  
        </script>  
    </head>
    <body>
        <input type="text" name="text" onkeyup="NumAndTwoDecimals(event , this);">  
    </body>
</html>

回答by iConnor

Your question is very hard to understand but if you want to check that a string has only 2 decimals then you can just do this

你的问题很难理解,但如果你想检查一个字符串是否只有 2 个小数,那么你可以这样做

if( value.match(/\./g).length === 2 ) {
    // Number has 2 decimals eg. 1.2.3
} else {
   // Number is incorrect eg. 1.2.3.4
}

or if you want 1.2then

或者如果你想1.2那么

if( value.match(/\./g).length === 1 ) {
    // Code....
}

回答by Pradeep

$('.number').keypress(function(evt){
    var str = $(this).val();
    var index = str.indexOf('.');
    if(index==-1){index=0;}else{index= index+1;}
    var extrapoint = str.indexOf('.',index);
    if(extrapoint>0){$(this).val(str.slice(0,-1));}
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
    var validNumber = new RegExp(/^\d*\.?\d*$/);
    var lastValid = $(this).val();
    if (validNumber.test($(this).val()))
    {
        lastValid = $(this).val();
    } 
    else
    {
        $(this).val(lastValid);
    }
});