Make an html number input always display 2 decimal places

后端 未结 8 477
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 05:09

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?

相关标签:
8条回答
  • 2020-11-30 05:49

    an inline solution combines Groot and Ivaylo suggestions in the format below:

    onchange="(function(el){el.value=parseFloat(el.value).toFixed(2);})(this)"
    
    0 讨论(0)
  • 2020-11-30 05:55

    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.

    0 讨论(0)
  • 2020-11-30 05:59

    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.

    0 讨论(0)
  • 2020-11-30 05:59

    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.

    0 讨论(0)
  • 2020-11-30 06:01

    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);
        };
    
    0 讨论(0)
  • 2020-11-30 06:03

    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);
        };
    
    0 讨论(0)
提交回复
热议问题