Is there a float input type in HTML5?
Asked Answered
S

13

1170

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 is simply (in the latest version of Chrome, anyway), an "updown" control with integers, not floats:

<input type="number" id="totalAmt"></input>

Is there a floating point input element native to HTML5, or a way to make the number input type work with floats, not ints? Or must I resort to a jQuery UI plugin?

Samples answered 25/9, 2013 at 17:51 Comment(0)
H
2416

The number type has a step value controlling which numbers are valid (along with max and min), which defaults to 1. This value is also used by implementations for the stepper buttons (i.e. pressing up increases by step).

Simply change this value to whatever is appropriate. For money, two decimal places are probably expected:

<label for="totalAmt">Total Amount</label>
<input type="number" step="0.01" id="totalAmt">

(I'd also set min=0 if it can only be positive)

If you'd prefer to allow any number of decimal places, you can use step="any" (though for currencies, I'd recommend sticking to 0.01). In Chrome & Firefox, the stepper buttons will increment / decrement by 1 when using any. (thanks to Michal Stefanow's answer for pointing out any, and see the relevant spec here)

Here's a playground showing how various steps affect various input types:

<form>
  <input type=number step=1 /> Step 1 (default)<br />
  <input type=number step=0.01 /> Step 0.01<br />
  <input type=number step=any /> Step any<br />
  <input type=range step=20 /> Step 20<br />
  <input type=datetime-local step=60 /> Step 60 (default)<br />
  <input type=datetime-local step=1 /> Step 1<br />
  <input type=datetime-local step=any /> Step any<br />
  <input type=datetime-local step=0.001 /> Step 0.001<br />
  <input type=datetime-local step=3600 /> Step 3600 (1 hour)<br />
  <input type=datetime-local step=86400 /> Step 86400 (1 day)<br />
  <input type=datetime-local step=70 /> Step 70 (1 min, 10 sec)<br />
</form>

As usual, I'll add a quick note: remember that client-side validation is just a convenience to the user. You must also validate on the server-side!

Hexosan answered 25/9, 2013 at 18:48 Comment(13)
To respond to @Elfayer's edit: quotes are optional in HTML unless you want to use certain characters. Personally I prefer to omit them where possible for better readability.Hexosan
This is not working correctly in latest versions of Firefox: bugzilla.mozilla.org/show_bug.cgi?id=1003896Yongyoni
To summarise that bug, FireFox is now truncating 0s where possible, so 4.10 will appear as 4.1. Still technically correct behaviour (the spec just requires it to show an appropriate floating-point representation), but a bad UI in the case of currency. I'd encourage people to vote for that bug. Looks like they might push for a new standard attribute to control the display.Hexosan
@Dave: Yes, technically, omitting quotes is fine, bit it introduces a host of potential issues. First, a subset of characters are handled differently in different browsers and versions thereof. If you choose not to use quotes, then you must be constantly cognizant of which characters will cause problems in each browser and version. That's a lot of mental power devoted to something that's not necessary to worry about at all if you just use quotes. (cont.)Revision
Second, while you may be fine with worrying about the rules of which characters are fine and which aren't, the developer that comes behind you probably won't be. That then requires that they either endure the arduous task of adding quotes to all the attributes you left unquoted or worse, simply introduce problems into the code which they might not even understand the source of. Finally, since sometimes you will have to use quotes, the code then looks inconsistent with some attributes quoted and others not.Revision
is it possible to hide the number incrementorsCriollo
@Criollo see here: https://mcmap.net/q/45393/-can-i-hide-the-html5-number-input-s-spin-box/1180785 but be sure to read the comments for each answer; it looks like all options have drawbacks, and you'll need to see what fits your particular needs.Hexosan
@Hexosan : Should the data be stored in a decimal (10,2) in the database or should it use something else? I'm asking because when I use this kind of input type with step, everything after the dot does not get inserted. I tried converting with floatval() but it does not work. When I enter 37.50 in the input mysql stores the number as 37.00. Have you gotten a clue? #43164912Zosema
<input type="number" step="0.01"> if i use like this its working from me but i'm trying to add manually not accepting .can we possible to add manuallyContrition
People should really remember and learn to use XHTML Standards... It answers simple questions like the one about quotes.. I forced myself to learn these standards many many many many years ago.... w3.org/TR/xhtml1/#h-4.4 All attribute values must be quoted, even those which appear to be numeric. Omiitting quotes is just asking for trouble.. More so if you have dynamic content/values..Shellans
Steps on the datetime-local don't seem to work in Google Chrome 62.0.3202.94, what browsers had you in mind when writing your answer back in 2013?Eury
@Eury step on datetime-local didn't fully work back then either. I added them because it's in the spec and I wanted people to be able to see what does and does not work. It's unfortunate that it still hasn't happened. Probably turned out to be much harder than they expected. It should work for things like whole minute / hour / day steps though (at least it does in Chrome 62; only the last example in the snippet I posted doesn't work).Hexosan
I can type eee---+++----++++eee into those controls in Chrome. Doesn't look like float number to me.Nomi
A
210

Via: http://blog.isotoma.com/2012/03/html5-input-typenumber-and-decimalsfloats-in-chrome/

But what if you want all the numbers to be valid, integers and decimals alike? In this case, set step to “any”

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

Works for me in Chrome, not tested in other browsers.

Aerophone answered 23/7, 2014 at 21:25 Comment(4)
Chrome => Works perfect Safari => Will not show error message, and if not number it will not pass to server IE => Version less than 10 not, worksCamorra
Unfortunately in chrome it allows you to enter multiple decimal points, for instance an IP address.Palfrey
@Palfrey newer versions of chrome this is fixed. This should be the acepted answer nowadays.Stirling
in FireFox it allows to input anything but validation will be failed. Still think this is the best answerDauphine
P
33

You can use:

<input type="number" step="any" min="0" max="100" value="22.33">
Photomap answered 15/3, 2016 at 18:39 Comment(0)
E
29

You can use the step attribute to the input type number:

<input type="number" id="totalAmt" step="0.1"></input>

step="any" will allow any decimal.
step="1" will allow no decimal.
step="0.5" will allow 0.5; 1; 1.5; ...
step="0.1" will allow 0.1; 0.2; 0.3; 0.4; ...

Eastward answered 25/2, 2018 at 19:46 Comment(0)
Q
14

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 :

  • 48-57 equal to 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
  • 0 is Backspace(otherwise need refresh page on Firefox)
  • 46 is 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.)

Quintal answered 14/4, 2016 at 11:14 Comment(6)
Feels backward. How about copy & paste in the field?Aerophone
use this method, but need validation before inserting @MichalStefanowQuintal
Hack for input, hack for copy & paste, hack on top of a hack = bad practice. We have 2017Aerophone
Where you read any password inputs ? Who care which method using after a session ? No, we have 1856 ! Try another user !Quintal
Sounds too complicated, but, reasoning on this method versus other mentioned not providedRiarial
i added || event.ctrlKey to allow basic copy pasting. But I would not use this approach if it wasn't a prototypePromiscuous
C
12

yes this is the correct answer:

step="any"

This is more efficient. Trust me.

<input type="number" step="any">

document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault();
alert("Your nnumber is: "+document.getElementById('n1').value)
alert("This works no ? :) please upvote")
})
<form id="form1">
<input type="number" step="any" id="n1">
<button type="submit">Submit</button>
</form>
<!-- UPVOTE :)-->
Cloakanddagger answered 18/4, 2021 at 13:36 Comment(0)
A
11

I do so

 <input id="relacionac" name="relacionac" type="number" min="0.4" max="0.7" placeholder="0,40-0,70" class="form-control input-md" step="0.01">

then, I define min in 0.4 and max in 0.7 with step 0.01: 0.4, 0.41, 0,42 ... 0.7

Aphis answered 13/6, 2017 at 14:26 Comment(0)
B
11

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

Bernadinebernadotte answered 14/9, 2020 at 7:44 Comment(0)
E
7

I just had the same problem, and I could fix it by just putting a comma and not a period/full stop in the number because of French localization.

So it works with:

2 is OK

2,5 is OK

2.5 is KO (The number is considered "illegal" and you receive empty value).

Emphasize answered 9/3, 2016 at 12:13 Comment(1)
add lang="en" to input or any parent and it will start using english number styleVo
W
7
<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.

Winsome answered 28/10, 2020 at 6:11 Comment(0)
R
4

Using React on my IPad, type="number" does not work perfectly for me. For my floating point numbers in the range between 99.99999 - .00000 I use the regular expression (^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$). The first group (...) is true for all positive two digit numbers without the floating point (e.g. 23), | or e.g. .12345 for the second group (...). You can adopt it for any positive floating point number by simply changing the range {0,2} or {0,5} respectively.

<input
  className="center-align"
  type="text"
  pattern="(^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)"
  step="any"
  maxlength="7"
  validate="true"
/>
Roe answered 10/12, 2020 at 9:44 Comment(0)
B
4

This topic (e.g. step="0.01") relates to stepMismatch and is supported by all browsers as follows: enter image description here

Bimanous answered 21/1, 2021 at 11:24 Comment(0)
P
2

If any of the methods doesn't work you can use parse float.

const totalAmt = document.getElementById("totalAmt");


totalAmt.addEventListener("change", (e)=>{
      // e.preventDefault(e);
      const result = parseFloat(e.target.value);
     console.log(result)
});
<input type="text" id="totalAmt" />
Peder answered 18/9, 2021 at 12:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.