Make an html number input always display 2 decimal places

后端 未结 8 524
伪装坚强ぢ
伪装坚强ぢ 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: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

    
    

    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.

提交回复
热议问题