8

I have an input field which I want to restrict so that the user only can input a number with the maximum of two decimals. Want to do this using jQuery.

Could I use jQuery toFixed() function somehow?

Thanx!

Ismailp
  • 2,333
  • 4
  • 37
  • 66
  • Why do you want using jQuery? You can do the same using "maxlenght=2" in html... Next, if you want to be sure that the user can insert only decimals, you can make a function called on event "onkeypress" – AleVale94 May 13 '12 at 09:41
  • Sounds like you want to validate a money field. Maybe this will help: http://javascriptbymallik.blogspot.com/2009/08/how-to-check-two-decimal-validation-in.html – Tim May 13 '12 at 09:50

9 Answers9

15

An alternative approach with a regular expression:

    $('#id').on('input', function () {
        this.value = this.value.match(/^\d+\.?\d{0,2}/);
    });

The id selector can be replaced by a css selector.

Tegge
  • 329
  • 3
  • 7
  • That's the best! – senty Dec 07 '18 at 12:43
  • Yup that is the best answer indeed. One more thing, I find that the expression `this.value = this.value.toFixed(2)` is not working because it assumes that input is always a float – Leonidas Oct 15 '19 at 08:47
12
$('input#decimal').blur(function(){
    var num = parseFloat($(this).val());
    var cleanNum = num.toFixed(2);
    $(this).val(cleanNum);
    if(num/cleanNum < 1){
        $('#error').text('Please enter only 2 decimal places, we have truncated extra points');
        }
    });

Here is a fiddle http://jsfiddle.net/sabithpocker/PD2nV/

Using toFixed will anyhow cause approximation 123.6666 -> 123.67 If you want to avoid approximation check this answer Display two decimal places, no rounding

Community
  • 1
  • 1
sabithpocker
  • 15,274
  • 1
  • 42
  • 75
4

A HTML5 solution:

<input type="number" step="0.01" />

Demo

If you want to style invalid inputs (some browsers do it by default), you can use :invalid selector:

input:invalid {   box-shadow: 0 0 1.5px 1px red;   }

Note this approach won't attempt to truncate the number automagically, but if the user enters more than two decimal digits, the input will become invalid, and thus the form won't be submitted:

Screenshot on Firefox

Oriol
  • 274,082
  • 63
  • 437
  • 513
3
<input type="text" name="amount1" id="amount1" class="num_fld Amt" onkeypress="return check_digit(event,this,8,2);" size="9" value="" maxlength="8" style="text-align:right;" />

The following function will restrict decimals according to your need of decimal places and also restrict more than one dot

function check_digit(e,obj,intsize,deczize) {
    var keycode;

    if (window.event) keycode = window.event.keyCode;
    else if (e) { keycode = e.which; }
    else { return true; }

    var fieldval= (obj.value),
        dots = fieldval.split(".").length;

    if(keycode == 46) {
        return dots <= 1;
    }
    if(keycode == 8 || keycode == 9 || keycode == 46 || keycode == 13 ) {
        // back space, tab, delete, enter 
        return true;
    }          
    if((keycode>=32 && keycode <=45) || keycode==47 || (keycode>=58 && keycode<=127)) {
         return false;
    }
    if(fieldval == "0" && keycode == 48 ) {
        return false;
    }
    if(fieldval.indexOf(".") != -1) { 
        if(keycode == 46) {
            return false;
        }
        var splitfield = fieldval.split(".");
        if(splitfield[1].length >= deczize && keycode != 8 && keycode != 0 )
            return false;
        }else if(fieldval.length >= intsize && keycode != 46) {
            return false;
        }else {
            return true;
        }
    }
}
Oriol
  • 274,082
  • 63
  • 437
  • 513
jawaharlal
  • 39
  • 1
2
$("#myInput").focusout(function() {
    if ($(this).val().length > 2 || isNaN(Number($(this).val())) {
        alert("Wrong number format");
    }
});
Lidor
  • 394
  • 9
  • 16
0

Try this for all symbols:

inputField.value.replace(/(\...)(.)/, "$1");

or this for numbers:

inputField.value.replace(/(\.[0-9][0-9])([0-9])/, "$1");

I found this method here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Example:_Switching_words_in_a_string

0
<input type="text" id="decCheck" onkeyup="decimalCheck();"/>

<script>
function decimalCheck(){
var dec = document.getElementById('decCheck').value;
if(dec.includes(".")){
    var res = dec.substring(dec.indexOf(".")+1);
    var kl = res.split("");
    if(kl.length > 1){
     document.getElementById('decCheck').value=(parseInt(dec * 100) / 
      100).toFixed(2);
    }
  }
}
</script>
Heinrich
  • 1
  • 1
0

A similar solution with a backspace hit on reaching more than 2 decimal places.

function limitDec(id) {
  // find elements
  var amt = $("#testdec")

  // handle keyup
  amt.on("keyup", function() {
    if (isNaN(amt.val())) {
      amt.val(0);
    }
    if (amt.val().indexOf(".") > -1 && (amt.val().split('.')[1].length > 2)) {
      amt.val(amt.val().substring(0, amt.val().length - 1));
    }
  })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="text" id="testdec" onkeyup="limitDec(this.id)" />
Soumav
  • 385
  • 1
  • 6
  • 25
0
//This Regex will take negative number with - (minus) sign:

$('#id').on('input', function () {
    this.value = this.value.match(/^[-]?\d*\.?\d{0,2}/);
});

//This regex will not take negative number or - (minus) sign:

$('#id').on('input', function () {
    this.value = this.value.match(/^\d+\.?\d{0,2}/);
});
kzhimel
  • 11
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 14 '23 at 00:50