Skip to content Skip to sidebar Skip to footer

Force Input Number Decimal Places Natively

I'd like to force an to always have 2 decimals to enter accounting data. I've managed to do that using JavaScript Is there any way to han

Solution 1:

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.


Solution 2:

You can use this:

function force2decimals(event) {
  var value = $(event).val();
  var format_val = parseFloat(value).toFixed(2);
  $(event).val(format_val);
}
<input type="number" step="0.01" id="input" onchange="force2decimals(this)" value="1.00" />

I hope this was helpful.


Post a Comment for "Force Input Number Decimal Places Natively"