Value overflows with <input type=”number”/>

Problem

We recently hit a problem where users pasting large numbers in a <input type="number"/> (part of a query input box), causing a wrong result. After further investigation, we realized that numbers (integer or floating points) exceeding 2^51 causes problems in Firefox, and probably just a bigger precision would cause problems in chrome.

At the time of this writing, the latest stable firefox is 60.5.1, and opening the snippet below in that browser rounds 0.060693571726285485 to 0.0606935717262855.

If this is a problem, then your project/organization requires you to work with these big of a precision. An unusual use case considering no UI framework libraries out there polyfills this problem. I tried so hard searching, and can’t find anything.

Workaround

The solution is to use and augment type="text" so it will act as a type="number" as much as possible. Before we begin, the following is my provisional solution:

The solution starts with adding onkeypress event handler and calling event.preventDefault() and setting event.returnValue = false; on invalid input, thus ensuring the input value is a number (float or integer). The following contains our javascript snippet for the onkeypress handler:

When onkeypress is called, let inputTextValue = theEvent.srcElement.value; contains the current input text value without the just clicked key value, hence we concatenate them.

After the concatenation, we apply the regex test. Our regex is /^[-]?[0-9]*\.?[0-9]*$/, which provides the following properties that we would like in our number input element:

  • Allows negatives. You can start typing just - and it will be valid.
  • Allows one decimal point. You can start typing 1234. and that would be valid. Hopefully, once you parse the value, you do something like Number.parseFloat("1234.") which results in 1234.

That’s it!

Next Steps

This solution is very simple but it’s missing a couple of things. For instance, it can’t take a step and spinner parameters. I will explore these avenues next time. I doubt we can stick to a native solution like this time, but we’ll see. Chances are, we’ll use UI frameworks, like angular/react to make those extra UI elements easier to play with.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.