Allow only numbers and one decimal point javascript

Guys and gals i have this piece of JavaScript code that only allows for numbers and one decimal period. The problem i'm having is that when i tab over to my textbox controls it highlights the value but i have press backspace to erase then enter a number. That is an extra keystroke that i want to prevent.

Props to the guy who created it found (http://www.coderanch.com/t/114528/HTML-CSS-JavaScript/decimal-point-restriction) and here is the code. I put this on keyUp event.

 <script>
  // Retrieve last key pressed.  Works in IE and Netscape.
  // Returns the numeric key code for the key pressed.
  function getKey(e)
  {
    if (window.event)
       return window.event.keyCode;
    else if (e)
       return e.which;
    else
       return null;
  }
  function restrictChars(e, obj)
  {
    var CHAR_AFTER_DP = 2;  // number of decimal places
    var validList = "0123456789.";  // allowed characters in field
    var key, keyChar;
    key = getKey(e);
    if (key == null) return true;
    // control keys
    // null, backspace, tab, carriage return, escape
    if ( key==0 || key==8 || key==9 || key==13 || key==27 )
       return true;
    // get character
    keyChar = String.fromCharCode(key);
    // check valid characters
    if (validList.indexOf(keyChar) != -1)
    {
      // check for existing decimal point
      var dp = 0;
      if( (dp = obj.value.indexOf( ".")) > -1)
      {
        if( keyChar == ".")
          return false;  // only one allowed
        else
        {
          // room for more after decimal point?
          if( obj.value.length - dp <= CHAR_AFTER_DP)
            return true;
        }
      }
      else return true;
    }
    // not a valid character
    return false;
  }
</script>

asked Jan 30, 2013 at 17:00

Allow only numbers and one decimal point javascript

3

<input type="text" class="decimal" value="" />

And in Js use this

$('.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); 
});

Check this fiddle: http://jsfiddle.net/2YW8g/

THis worked for me, i have taken this answer from "Nickalchemist" and take none of its credit.

Allow only numbers and one decimal point javascript

Hitesh Modha

2,6905 gold badges27 silver badges47 bronze badges

answered Jan 27, 2014 at 14:42

sohaibsohaib

8271 gold badge12 silver badges9 bronze badges

1

If you can't use an already stable and well-know library, you can try something like this:

document.write('<input id="inputField" onkeyup="run(this)" />');

function run(field) {
    setTimeout(function() {
        var regex = /\d*\.?\d?/g;
        field.value = regex.exec(field.value);
    }, 0);
}

I know it doesn't prevent the wrong char to appear, but it works.

PS: that setTimeout(..., 0) is a trick to execute the function after the value of the field has already been modified.

answered Jan 30, 2013 at 17:35

Alex OliveiraAlex Oliveira

8831 gold badge9 silver badges25 bronze badges

5

Here is a sample solution that will accept a number with one(1) decimal point only. e.g 1.12, 11.5

Enter a number with one(1) decimal point only<br />
<input type="text" id="decimalPt"> <br />

$('.decimalPt').keypress(function(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode == 8 || charCode == 37) {
    return true;
  } else if (charCode == 46 && $(this).val().indexOf('.') != -1) {
    return false;
  } else if (charCode > 31 && charCode != 46 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
});

Take a look at this: https://jsfiddle.net/sudogem/h43r6g7v/12/

answered Sep 21, 2016 at 15:19

Arman OrtegaArman Ortega

2,73327 silver badges27 bronze badges

1

I think it would be best to use something that already exists... like Masked Input Plugin with jQuery

answered Jan 30, 2013 at 17:04

mihaimmmihaimm

5122 silver badges6 bronze badges

0

Try this,

$('input').on('keydown', function (event) {
    return isNumber(event, this);
});
function isNumber(evt, element) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if ((charCode != 190 || $(element).val().indexOf('.') != -1)  // “.” CHECK DOT, AND ONLY ONE.
            && (charCode != 110 || $(element).val().indexOf('.') != -1)  // “.” CHECK DOT, AND ONLY ONE.
            && ((charCode < 48 && charCode != 8)
                    || (charCode > 57 && charCode < 96)
                    || charCode > 105))
        return false;
    return true;
}

answered Oct 14, 2015 at 10:35

I solve my problem with like this.

const sanitize = (value = '') => value.replace(/(-(?!\d))|[^0-9|-]/g, '') || ''

export const toNumeric = value => {
  let digits = sanitize(value)

  // parseInt with 0 fix/avoid NaN
  digits = parseInt(0 + digits)
  let newValue = digits.toString().padStart(4, 0)

  return newValue
}

answered Feb 5, 2021 at 5:51

How do I limit decimal places in JavaScript?

To limit decimal places in JavaScript, use the toFixed() method by specifying the number of decimal places..
Rounds the number..
Converts it into a string..
Returns the number as a string..

How do I allow only numbers in JavaScript?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.

How do I restrict the number of decimal places?

Now you can limit the decimal places. Select the number cell and in the Menu, go to Format > Number > More Formats > Custom number format.

How do you restrict numbers in JavaScript?

The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.