How to Allow 2 Decimals in an Input of Type "Number" in HTML

- 👤 Andrés Cruz

🇪🇸 En español

How to Allow 2 Decimals in an Input of Type "Number" in HTML

When defining some HTML fields such as numeric type, we may want to change the specific number of decimals. For example, when it comes to prices, it is common to want users to enter values to exactly two decimal places.
 

In this article we are going to learn how we can customize the number of decimals in an HTML field.

The <input type="number"> element in HTML allows users to enter numerical values; However, by default, it does not allow limiting the number of decimals using an attribute that indicates the minimum amount or basis for defining the number of decimals.

We can use the step attribute to define the interval between values but this does not mean that users enter exactly two decimal places.

To make an input field accept only two decimal places, we can combine HTML with JavaScript; First, we create an input field of type “number” and set the step attribute to "0.01" to allow two decimal places.

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

Using JavaScript, we add an event handler for the input event. When the user enters a value, we check if it has two decimal places. If not, we automatically round the value to two decimal places.

const priceInput = document.getElementById("price");

// Ensure that the initial value is in the correct format
priceInput.value = priceInput.valueAsNumber.toFixed(2);

// Handler that ensures the value is in the correct format when modified
priceInput.addEventListener("input", function (event) {
  event.target.value = event.target.valueAsNumber.toFixed(2);
});

And this is it, in the end it all comes down to adding an event for when the user types and rounding to two decimal places if necessary.

Summary, many times we have a text field which we want to represent a price or ultimately a numerical value with a decimal part; if you are up to date with HTML5, you know that you can define a field of type number

Tengo un <input type = "number">

The problem is, it will only accept integer numbers; If you want a decimal part, which is our goal, you have to define the step parameter, to indicate the interval; in our case, we want it to be two decimal places:

step=".01"

If you wanted, for example, 3

step=".001"

Definitely:

<input type = "number" step=".01">

I agree to receive announcements of interest about this Blog.

Let's see how we can limit the number of decimals in a field in HTML. Many times we have a text field which we want to represent a price or ultimately a numerical value with a decimal part; for that we use the step attribute.

| 👤 Andrés Cruz

🇪🇸 En español