Decimals and numeric input fields

I learned something new about number input fields. So, I already knew about the number input type (as well as the other different types of input fields you can have: color, range, search, date and time). I also knew about the min and max attributes, — but I didn’t know about the step attribute. Until…

I learned something new about number input fields.

So, I already knew about the number input type (as well as the other different types of input fields you can have: color, range, search, date and time). I also knew about the min and max attributes, — but I didn’t know about the step attribute.

Until today, I’ve only ever used number inputs for integers, not floats (decimals). So of course, I thought this would work:

<input type="number" name="price">

And it does work, as long as that price is in whole dollars, no cents. But as soon as you put a decimal value in there, any modern browser will stop the form from being submitted.

If you want a number input to accept decimal values, you need to add the step attribute. If you want to accept a price — that is, a decimal value up to hundredths — you’d do this:

<input type="number" name="price" step="0.01">

I created a little demo of this very thing in action. (Note: most modern browsers, and even Internet Explorer 11, will provide built-in form validation if the input value does not match the requirements. In older versions of iOS Safari, however, this is not the case.)

One more fun fact: when you retrieve the field’s value in JavaScript, like this:

form.price.value

That value is returned as a string, not as a numeric value — even though the field is defined as a number. Make sure you use the correct parse function to get the numeric value: parseInt() for integers, parseFloat() for decimals.

Form fields have a handy little property called valueAsNumber, but Internet Explorer doesn’t seem to like it. It always returns NaN for me, so I don’t recommend using it if you need to support IE.

I’m not sure if I should be ashamed because as a (self-proclaimed) front-end developer I never knew this, or if I should be happy because I learned something. I think it’s a little of both. As my dad always says, “we’re not born knowing these things.”

Leave a Reply

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.

Related