How to prevent keypress two digits after a decimal number?

后端 未结 5 2000
花落未央
花落未央 2020-12-31 10:06

I have got a task to prevent keypress two digits after a decimal number. My jquery file is

$(function(){ 
    $(\'#name\').bind(\'paste\', function(){
             


        
5条回答
  •  粉色の甜心
    2020-12-31 10:44

    Another Possible Solution(Demo):

    Number.prototype.toFixedDown = function(digits) {
      var n = this - Math.pow(10, -digits)/2;
      n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
      return n.toFixed(digits);
    }
    $( function() {
        $('.two-digits').keyup(function(){
            if($(this).val().indexOf('.')!=-1){         
                if($(this).val().split(".")[1].length > 2){                
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixedDown(2);
                }  
             }            
             return this; //for chaining
        });
    });
    

提交回复
热议问题