Yann Bertrand Yann Bertrand - 3 months ago 18
HTML Question

Force input number decimal places natively

I'd like to force an

<input type="number" step="0.01" />
to always have 2 decimals to enter accounting data.

I've managed to do that using JavaScript



document.getElementById('input').addEventListener('change', force2decimals);

function force2decimals(event) {
event.target.value = Number(Math.round(event.target.value * 100) / 100).toFixed(2);
}

<input type="number" step="0.01" id="input" value="1.00" />





Is there any way to handle this natively?

I know about the
step
attribute, the "duplicate answer" doesn't reply to my question.

Answer

It could be done by this:

document.getElementById('input').addEventListener('change', force2decimals);

function force2decimals(event) {
	event.target.value = parseFloat(event.target.value).toFixed(2);
}
<input type="number" step="0.01" id="input" value="1.00" />

There is no way to do this "natively" in HTML5.