Kumar
Kumar

Reputation: 1277

How to avoid Decimal values in input type number

How to avoid Decimal values from input of Number in HTML5. Currently it allows user to type decimal value.

Upvotes: 119

Views: 228509

Answers (21)

user1458963
user1458963

Reputation: 181

For react users I suggest tu use

<input type='number' onKeyDown={(e) =>(e.key === "." || e.key === ",") && e.preventDefault()/>

Upvotes: 0

Dinko Zorić
Dinko Zorić

Reputation: 1

Not pretty but seems to work. Allows free edit, corrects on lose focus.

For range between -100 to 100

<input 
onblur="val = parseInt(this.value.replace(/[^-0-9]/g, '')) || ''; this.value = Math.min(Math.max(val, -100), 100);"
oninput="val = parseInt(this.value.replace(/[^-0-9]/g, '')) || ''; this.value = val ? Math.min(Math.max(val, -100), 100) : '';">

Upvotes: 0

Wouter
Wouter

Reputation: 790

I encountered the same challenge and a combination of answers here helped me to get it to work on Android, iOS and Chrome and Firefox on the desktop. I needed the input field to only accept numeric values without decimals. This is what I came up with:

<input id="inputField" type="number" inputmode="numeric" pattern="[0-9]*" />
document.getElementById("inputField").addEventListener('beforeinput', event => {
  const char = event.data;
  if (char != null && char !== '' && !/^[0-9]*$/.test(char)) {
    event.preventDefault();
  }
});

It's pretty similar to the solution proposed by TyphousCrane654. The differences are that it does not allow for decimal numbers and it also allows for the backspace button being pressed. It's also good to mention that it supports pasting in valid values, but not invalid values. I hope it helps someone else (or at least myself in the future).

You can test it yourself in this JSFiddle.

Upvotes: 0

Eyayu Tefera
Eyayu Tefera

Reputation: 931

This worked for me for Angular 16, the sample rejects negative numbers also

 <input matInput type="number" placeholder="Price" required 
                   onkeydown="if(this.key==='.'){this.preventDefault();}"
                   oninput="this.value = Math.abs(this.value.replace(/[^0-9]*/g,''))">

if you want it to accept negative number you can use

 <input matInput type="number" placeholder="Price" required formControlName="LimitPrice"
                   onkeydown="if(this.key==='.'){this.preventDefault();}"
                  >

Upvotes: 0

Gianluca Petito
Gianluca Petito

Reputation: 13

This solution let user insert only numbers from 0 to 9

<input type="number" name="intero" oninput="this.value = this.value.replace(/[^0-9]/g, '')" />

Upvotes: 1

shrinath deshmukh
shrinath deshmukh

Reputation: 5

 For Angular Developers:
    
    <input type="number" min="1" (keydown)="keyDown($event)">
    
    keyDown(event) {
        if (event.key === '.' || 'e' || 'E') {
          event.preventDefault();
        }
      } 

Upvotes: -1

Shams Wali Sowmo
Shams Wali Sowmo

Reputation: 369

In case anyone still wondering a solution, here's a workaround I came up with:

const val = 33.15;

console.log(String(val).includes(".")) // true

if(String(val).includes(".")){
   // the number is decimal
} else {
  // the number is not decimal
}

Upvotes: 0

TyphousCrane654
TyphousCrane654

Reputation: 31

event.key and event.charCode are deprecated features and don't work well with mobile virtual keyboards. I've done some research and this seems to be the easiest way to make it work.
Tested in Chrome and Firefox on Windows, in Chrome on Android and in Safari on iOS and seems to be working perfectly.

document.getElementById("myInput").addEventListener('beforeinput', e => {
  if (!(Number(e.data) >= 0 && Number(e.data) <= 9)) {
    e.preventDefault();
  }
});
/* unnecessary */
#myInput {
width: 24ch;
}
<input type="number" inputmode="numeric" placeholder="only a number can go here" id="myInput">

By the way, this is my first post here, so please tell me if I'm doing anything wrong.

Upvotes: 3

Lakshan Dhanasekara
Lakshan Dhanasekara

Reputation: 11

Try this :

<input type="number"  value=""  min="0" oninput="this.value=(parseInt(this.value)||0)" onkeypress="return !(event.charCode == 45||event.charCode == 46||event.charCode == 43)"  class="form-control" step="any" />

Upvotes: 1

Omari Erick
Omari Erick

Reputation: 1

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode==46))
        return false;
    return true;     
}

Upvotes: 0

Hussain
Hussain

Reputation: 138

<input type="number" onkeypress="return event.charCode >= 48 && event.charCode <= 57"  name="quantity">

Upvotes: 1

Phalak
Phalak

Reputation: 39

@Html.TextBoxFor(model => model.num, new { @class = "form-control input-sm",@maxlength = 5 ,@oninput = "this.value = this.value.replace(/[^0-9]/g, '');"})

In MVC, above solution works.

Upvotes: -3

Npsad
Npsad

Reputation: 606

<input type="number" onkeydown="return event.keyCode !== 190"> 

This will Restrict period(.) input.For any Key restriction: https://css-tricks.com/snippets/javascript/javascript-keycodes/

Upvotes: 5

nik-noor-akmal
nik-noor-akmal

Reputation: 19

You guys can try this This function does not allow user to paste unwanted characters and also disallow user to enter .+-E

var inputBox = document.getElementById("inputBox");
            
                var invalidChars = [
                    "-",
                    "+",
                    "e",
                    "."
                ];

                inputBox.addEventListener("input", function() {
                    this.value = this.value.replace(/[e\+\-\.]/gi, "");
                });
                

                inputBox.addEventListener("keydown", function(e) {
                    if (invalidChars.includes(e.key)) {
                        e.preventDefault();
                    }
                });
 
         
<input type="number" id="inputBox" >

`

If error occured in your JS. You can add this `$(document).ready(function() { code });

Upvotes: 1

Terrorbladezz
Terrorbladezz

Reputation: 91

A simple regex can help sort with this issue .

var re = new regExp('[.]+) ;
if(!re.test(num)){listOfNumbers.push(num)};

not letting the user type in a '.' on the input might not be a viable option when you are dealing with multiple cultures and interpretations of '.'.

Upvotes: 0

Stevenfowler16
Stevenfowler16

Reputation: 1000

I ended up checking to see if a user types in a period then preventing the event from propagating.

Edit: A better approach. The key press event has been deprecated. Also added in a regex to strip out everything but numbers [0-9] on paste.

<input type="number" onkeydown="if(event.key==='.'){event.preventDefault();}"  oninput="event.target.value = event.target.value.replace(/[^0-9]*/g,'');">

Caution Experimental. Only partially works on chrome: Wanted to look at a great way to grab the pasted value strip everything out then have it placed in input as normal. With the above method you are relying on the event order to correct the input, then any event listeners will ideally fire after. The onpaste method will fire before the input event fires so you keep the flow of events correct. However when replacing the string with only numbers the decimal point would still sneak in. Looking to update this when I find a better solution.

<input type="number" onkeydown="if(event.key==='.'){event.preventDefault();}" onpaste="let pasteData = event.clipboardData.getData('text'); if(pasteData){pasteData.replace(/[^0-9]*/g,'');} " >

Upvotes: 52

user2575725
user2575725

Reputation:

Just plain example using parseInt()

<input type="number" oninput="this.value=(parseInt(this.value)||0)" placeholder="0-9" autofocus='' value='0' />

Upvotes: 14

Nigel Fds
Nigel Fds

Reputation: 813

Based on other answers here, I tried this:

<input id="storeId" min="0" pattern="[0-9]" onkeypress="return !(event.charCode == 46)" step="1" title="Must be an integer number" type="number" >

I just blocked input of dot, but again this does not block paste.

ASCII DOT . character is 46

Upvotes: 11

kneeki
kneeki

Reputation: 2692

An alternative to the supplied answers is to monitor the keypress while in the input. I personally like leaving the type="number" as an attribute. Here's a JSFiddle

<form action="#" method="post">
  Numbers: <input name="num" 
                  type="number"
                  min="1"
                  step="1"
                  onkeypress="return event.charCode >= 48 && event.charCode <= 57"
                  title="Numbers only">
  <input type="submit">
</form>

Upvotes: 131

Deepu Sasidharan
Deepu Sasidharan

Reputation: 5309

Use pattern attribute

<input type="number" name="num" pattern="[0-9]" title="Numbers only">

For more details http://www.w3schools.com/tags/att_input_pattern.asp

FIDDLE

Upvotes: 16

Kake_Fisk
Kake_Fisk

Reputation: 1165

You should post what you have tried when asking questions.

To use integers only, change the following attribute.

step="any"

to

step="1"

Upvotes: -1

Related Questions