Question

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

$(function(){ 
    $('#name').bind('paste', function(){
    var self = this;
    setTimeout(function() {
        if(!/^[a-zA-Z]+$/.test($(self).val()))
            $(self).val('');
    }, 0);    
           }); 

        $('#salary').bind('paste', function(){
    var self = this;
    setTimeout(function() {
        if(!/^\d*(\.\d{1,2})+$/.test($(self).val()))
            $(self).val('');
    }, 0);    
           }); 

    $('.decimal').keyup(function(){
        var val = $(this).val();
        if(isNaN(val)){
             val = val.replace(/[^0-9]./g,'');


             if(val.split('.').length>2) 
                 val =val.replace(/\.+$/,"");
        }
        $(this).val(val); 
    });
    });      

My html page is

<b>Name</b>
<input type="text" id="name"  /><br/>
<b>Salary</b>
<input type="text" id="salary"  class="decimal" />

here i want only write 2 digits after decimal,how can i do this? You can see my code in http://jsfiddle.net/V6s4B/

Was it helpful?

Solution

You can handle the key event before keyup on keypress, if the input is not to our liking we can disable the event from occurring. Something like this:

Update

Unfortunately my original answer below fails on certain numbers that can't be represented accurately as a float. Here is another solution that checks the position of the '.' character against the length of the string with a handy helper function.

jsFiddle

$('.decimal').keypress(function (e) {
    var character = String.fromCharCode(e.keyCode)
    var newValue = this.value + character;
    if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
        e.preventDefault();
        return false;
    }
});

function hasDecimalPlace(value, x) {
    var pointIndex = value.indexOf('.');
    return  pointIndex >= 0 && pointIndex < value.length - x;
}

Original answer

jsFiddle

$('.decimal').keypress(function (e) {
    var character = String.fromCharCode(e.keyCode)
    var newValue = this.value + character;
    if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
        e.preventDefault();
        return false;
    }
});

Note that parseFloat(newValue) * 100 % 1 > 0 evaluates to true if newValue contains a number that has more than 2 decimal places.

OTHER TIPS

$("#salary").keyup(function(){
    var number = ($(this).val().split('.'));
    if (number[1].length > 2)
    {
        var salary = parseFloat($("#salary").val());
        $("#salary").val( salary.toFixed(2));
    }
  });

http://jsfiddle.net/calder12/fSQpc/

Stop letters from going in the box, you'll have to put the two together I haven't time.

    if (this.value.match(/[^0-9]./g)) {
      this.value = this.value.replace(/[^0-9]./g, '');
      return false;
    }

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
    });
});

This might be helpful to some. I mixed the answers of this guy, @Tats_innit from https://stackoverflow.com/a/10514166/5382523 and @Rick Calder above.

EDIT also from this guy, isJustMe from https://stackoverflow.com/a/17289322 for the parseFloat with "|| 0". Because if the input's field is null or zero "NaN" is shown and you can't delete it.

HTML

<input type="text" name="txt_prod_price" id="txt_prod_price" class="form-control price" maxlength="20" placeholder="">

JAVASCRIPT (JQUERY)

$('.price').keypress(function(event) {

          if(event.which < 46 || event.which > 59) {
              event.preventDefault();
          } // prevent if not number/dot

          if(event.which == 46 && $(this).val().indexOf('.') != -1) {
              event.preventDefault();
          } // prevent if already dot

          var number = ($(this).val().split('.'));
          if (number[1].length > 2)
          {
           var price = parseFloat($("#txt_prod_price").val()) || 0;
           $("#txt_prod_price").val(price.toFixed(2));  
          }

      });

the "price" is pre-defined.

Note: still have buggy inputs but still kickin'. (y)

More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

I did it this way: Provided a class allow-only-numbers, for your input then:

  var numberOfDecimals = 2;
  $(document).on("input", ".allow-only-numbers", function () {
    var regExp = new RegExp('(\\.[\\d]{' + numberOfDecimals + '}).', 'g')    
    this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(regExp, '$1');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top