How to avoid Decimal values from input of Number in HTML5. Currently it allows user to type decimal value.
-
7This question has been aswered already: [html5 number input type that takes only integers](https://stackoverflow.com/questions/8808590/html5-number-input-type-that-takes-only-integers) – lucask May 05 '16 at 06:45
-
1I tried the pattern method, But i would like to have behaviour same as number field. in case of using pattern it doesn't validate until the value is submitted. Just like a number field doesn't allow user to type alphabets, is there any way i could stop period value too. – Kumar May 05 '16 at 08:39
17 Answers
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>

- 2,444
- 4
- 17
- 27
-
1This solution works great to avoid inputs other than numbers [0-9]. Perfect. – naamadheya Aug 22 '17 at 16:55
-
17It looks like this also disables backspace and delete keys in FireFox which isnt ideal when editing the input field. – AfromanJ Oct 13 '17 at 09:18
-
7you can still right-click paste to inject other inputs. – Antonio Nicolaas Teyken Jan 31 '18 at 08:58
-
-
This solution isn't working on Android. Did anyone find a way to fix this on Android? – Sundeep May 07 '21 at 10:54
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,'');} " >

- 880
- 1
- 7
- 22
-
3This is a perfect solution. Anyway, just a tip for Angular developers. onpaste is not allowed on input field, you have to use (paste) which does the same stuff as onpaste. Moreover, do not use event.* into onkeydown because, as Steven as said, is deprecaded. Instead i suggest to use $event on Angular application that should act as the same of event – Bugpirasi Nov 05 '20 at 16:59
-
-
You could just as easily set it to blank (or a default value) if that behavior is desired – Stevenfowler16 Feb 27 '23 at 18:42
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

- 5,193
- 10
- 40
- 97
-
30Just a note: This seems to only validate on submit of the form that the input is in; it doesn't prevent decimal input, nor does it indicate that the field is in error before the form is submitted. – Bernhard Hofmann Dec 14 '16 at 11:33
-
8Secondary note: 1.0 will return as valid which may or may not correct depending on your what you want. – Michael Feb 24 '17 at 14:58
-
3does not work as I want to check for decimals to be not included when user is typing. – Lonare Mar 07 '18 at 15:12
Just plain example using parseInt()
<input type="number" oninput="this.value=(parseInt(this.value)||0)" placeholder="0-9" autofocus='' value='0' />
-
works well. still allows the user to enter a 'fullstop' or 'period' character because `parseInt(0.)` returns `0`. but that makes sense mathematically, because when you enter `0.` without a number after the decimal, the assumption is that it's zero, so `0.` == `0.0`, which equals `0 ` when parsed to an integer. makes sense to me anyway... – camslice Mar 12 '20 at 11:38
-
This works well but not actual since html5. Only if old browsers support is critical – Andrey Doloka Jun 15 '20 at 08:10
-
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

- 803
- 2
- 12
- 29
<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/

- 508
- 4
- 12
-
On my side, if the use the dot on my numpad, the keyCode is 110. If I use the one with the letters, it's 190. I think both should be restricted. – Math M. May 05 '23 at 15:28
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 });

- 19
- 1
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" />

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

- 106
- 8
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.

- 11
- 2
You should post what you have tried when asking questions.
To use integers only, change the following attribute.
step="any"
to
step="1"

- 1,107
- 11
- 22
-
23using step attribute still allows user to type decimal value. Just like number field doesn't allow user to type alphabets, is there any way that i could restrict user to type float values – Kumar May 05 '16 at 08:41
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 '.'.

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

- 3,073
- 7
- 20
- 33
-
If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/31249995) – MD. RAKIB HASAN Mar 16 '22 at 09:21
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
}

- 54
- 7
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, '')" />

- 3
- 3
-
2Please [edit] your answer to provide more information as to how the code you've provided works, what you have changed, etc. Code-only answers might solve the problem of the original asker but they don't help future readers understand the solution. – LW001 Aug 06 '23 at 15:05
For Angular Developers:
<input type="number" min="1" (keydown)="keyDown($event)">
keyDown(event) {
if (event.key === '.' || 'e' || 'E') {
event.preventDefault();
}
}
@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.

- 9
- 1
-
2
-
in addition to @Beefster comment, please also read the comments under the question, you would see that Kumar already rejected the regex approach – NimaNr Dec 16 '20 at 17:57
-