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

- Andrés Cruz

En español

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.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.