According to html5.org, the \"number\" input type\'s \"value attribute, if specified and not empty, must have a value that is a valid floating point number.\"
Yet it
<input type="number" step="any">
This worked for me and i think is the easiest way to make the input field accept any decimal number irrespective of how long the decimal part is. Step attribute actually shows the input field how many decimal points should be accepted. E.g, step="0.01" will accept only two decimal points.
Based on this answer
<input type="text" id="sno" placeholder="Only float with dot !"
onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||
event.charCode == 46 || event.charCode == 0 ">
Meaning :
Char code :
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Backspace
(otherwise need refresh page on Firefox)dot
&&
is AND
, ||
is OR
operator.
if you try float with comma :
<input type="text" id="sno" placeholder="Only float with comma !"
onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||
event.charCode == 44 || event.charCode == 0 ">
Supported Chromium and Firefox (Linux X64)(other browsers I does not exist.)
I have started using inputmode="decimal"
which works flawlessly with smartphones:
<input type="text" inputmode="decimal" value="1.5">
Note that we have to use type="text"
instead of number
. However, on desktop it still allows letters as values.
For desktop you could use:
<input type="number" inputmode="decimal">
which allows 0-9
and .
as input and only numbers.
Note that some countries use ,
as decimal dividor which is activated as default on the NumPad. Thus entering a float number by Numpad would not work as the input field expects a .
(in Chrome). That's why you should use type="text"
if you have international users on your website.
You can try this on desktop (also with Numpad) and your phone:
<p>Input with type text:</p>
<input type="text" inputmode="decimal" value="1.5">
<br>
<p>Input with type number:</p>
<input type="number" inputmode="decimal" value="1.5">
Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode