12

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/

Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
Monica
  • 607
  • 4
  • 12
  • 31
  • i would validate the input, when the person is finished entering the Data, not while. This would make the whole thing easy. ...just an sugestion. – winner_joiner Mar 28 '13 at 11:28
  • Can u help me to do this? you can see my code on http://jsfiddle.net/V6s4B/ – Monica Mar 28 '13 at 11:30
  • 1
    I am not an interaction designer, but as a user I would not be too pleased when everything I type is immediately changed into something else. I would recommend either telling the user what kind of input is expected (before and after). – Lodewijk Bogaards Mar 28 '13 at 11:30
  • @mrhobo-I just want only two numbers after the decimal number. – Nithin Viswanathan Mar 28 '13 at 11:33
  • Out of usability reasons i would, write an information or an example which entries are allowed. If not some users might, think something is work with the website. – winner_joiner Mar 28 '13 at 11:41

5 Answers5

16

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.

Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
  • Wait am I the only one that can't type 1.11 or 2.22? It seems to bug on some inputs. – Rick Calder Mar 28 '13 at 11:47
  • Try mine, pretty sure it works, it worked with all the numbers I put in anyway, you'll just have to do some checking to make sure it has no letters, I'll add that too, give me a sec. Grrr fighting with the removing anything but numbers and have to run to work. The decimal functionality works though – Rick Calder Mar 28 '13 at 11:52
  • @Tyriar-Its only working on Jsfiddle.Its not working on my page – Nithin Viswanathan Mar 28 '13 at 12:06
  • Fixed the answer, used a different method. – Daniel Imms Mar 28 '13 at 12:13
  • @DanielImms- Its not working.While running this code all key in the keyboard is restricted.(Only for firefox) – Nithin Viswanathan Mar 29 '13 at 01:44
  • var newValue = this.value + character; This line assumes chars always entered at the end of the input, which is not always true and it makes code to fail, when it is not the case! – Igor Yalovoy Oct 02 '17 at 22:48
  • Can you suggest me i have also checked with only allow 0.5 value in textbox Example User can Only Enter 19.50,21.50,66.50. If User can enter 19.23 then it's become Error for me. – Jydipsinh Parmar Mar 12 '19 at 07:51
4
$("#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;
    }
Rick Calder
  • 18,310
  • 3
  • 24
  • 41
  • Your answer is correct but you mentioning only the two floating point.In above we cannot write any symbol or alphabetic on that textbox – Nithin Viswanathan Mar 28 '13 at 11:53
  • Yeah, I can give you the separate code to stop that, but I haven't got time to integrate the two together you'll have to do that. – Rick Calder Mar 28 '13 at 11:56
  • 1
    eh, as I said, 2 year old code that gets the job done. One extra line fixes the console error. You have nothing better to do than troll 2 year old responses? http://jsfiddle.net/fSQpc/49/ – Rick Calder Feb 25 '15 at 19:08
  • In this solution, we can add multiple decimal points, On first decimal, it restricts the user to add 2 digits after the decimal, and in case if you add second decimal then the solutions fail – bajran Mar 20 '19 at 09:35
0

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
    });
});
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
0

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

Quer
  • 405
  • 7
  • 16
-1

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');
});
MarwaAhmad
  • 808
  • 9
  • 21