I\'m making a form where the user can enter a dollar amount using an html number input tag. Is there a way to have the input box always display 2 decimal places?
an inline solution combines Groot and Ivaylo suggestions in the format below:
onchange="(function(el){el.value=parseFloat(el.value).toFixed(2);})(this)"
Pure html is not able to do what you want. My suggestion would be to write a simple javascript function to do the roudning for you.
So if someone else stumbles upon this here is a JavaScript solution to this problem:
Step 1: Hook your HTML number input box to an onchange
event
myHTMLNumberInput.onchange = setTwoNumberDecimal;
or in the html code if you so prefer
<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />
Step 2: Write the setTwoDecimalPlace method
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(2);
}
By changing the '2' in toFixed
you can get more or less decimal places if you so prefer.
Look into toFixed for Javascript numbers. You could write an onChange function for your number field that calls toFixed on the input and sets the new value.
What other folks posted here mainly worked, but using onchange
doesn't work when I change the number using arrows in the same direction more than once. What did work was oninput
. My code (mainly borrowing from MC9000):
HTML
<input class="form-control" oninput="setTwoNumberDecimal(this)" step="0.01" value="0.00" type="number" name="item[amount]" id="item_amount">
JS
function setTwoNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(2);
};
The accepted solution here is incorrect. Try this in the HTML:
onchange="setTwoNumberDecimal(this)"
and the function to look like:
function setTwoNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(2);
};