Search code examples
htmlnumber-formatting

How to define HTML's input field when I need to store floating numbers of varying precision?


I need an input form element that can store numbers such as these:

  • 4.6050927694997500
  • 0.0384623400229826
  • -0.0000317620199043
  • etc

Currently to be able to enter such a number, HTML spec requires you to set up a step value, like so:

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

It feels a little weird for me to define a step value so small with so many zeroes.

Is there a better way to do this? Should I just be using a text field type for my floating numbers instead of the number?


Solution

  • Yes, it is good idea You have to use text field (it does not have up/down buttons – you can use JS to create them). It is good to use a pattern attribute to inform user the input is invalid.

    <!-- TRY THIS SNIPPET -->
    
    negative or positive
    <input pattern="-?[0-9]+(\.[0-9]+)?" value="0">
    <hr>
    
    only positive
    <input pattern="[0-9]+(\.[0-9]+)?" value="0">
    
    <hr>
    
    negative or positive supporting "scientific" format (eg. 5.3e-5)
    <input pattern="-?[0-9]+(\.[0-9]+)?([eE]-?[0-9]+)?" value="0">
    
    <hr>
    
    positive supporting "scientific" format (eg. 5.3e-5)
    <input pattern="[0-9]+(\.[0-9]+)?([eE]-?[0-9]+)?" value="0">
    
    <hr>
    Try entering some numbers (5, -5, 5.5, -5.5, -4.556e5, 4.556e5)

    Also (as in the case of type=number field) check it on the server (if it is sent).