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">
You can also use a decimal value: for example, a step of 0.3 will allow values such as 0.3, 0.6, 0.9 etc, but not 1 or 2. Now you don't get a validation error. Yay! Also note that if you only want to accept positive numbers, you'll want to add min=”0″.
Use the toFixed() method in JavaScript to format a number with two decimals. The toFixed() method formats a number with a specific number of digits to the right of the decimal.
We will use %. 2f to limit a given floating-point number to two decimal places.
Rounding to a certain number of decimal places4.737 rounded to 2 decimal places would be 4.74 (because it would be closer to 4.74). 4.735 is halfway between 4.73 and 4.74, so it is rounded up: 4.735 rounded to 2 decimal places is 4.74.
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: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With