Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

numbers

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"> 
like image 568
nubteens Avatar asked Dec 03 '15 03:12

nubteens


People also ask

Can input type number accept decimal?

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″.

How do I put 2 decimal places in HTML?

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.

How do I only allow 2 decimal places in Python?

We will use %. 2f to limit a given floating-point number to two decimal places.

How do you write a 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.


1 Answers

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

like image 109
Michael Benjamin Avatar answered Sep 23 '22 13:09

Michael Benjamin