nubteens nubteens - 2 months ago 4
HTML Question

Allow to 2 decimal places in <input type="number">

I have a

<input type="number">
and I want to restrict the input of the users to purely numbers or numbers with decimals up to 2 decimal places.

Basically, I am asking for a price input.

I wanted to avoid doing regex. Is there a way to do it?

<input type="number" required name="price" min="0" value="0" step="any">

Answer

Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places.

More details in the spec: 4.10.5.3.8 The step attribute