HTML5 Number Input - Always show 2 decimal places

后端 未结 15 2094
太阳男子
太阳男子 2020-11-28 05:43

Is there\'s any way to format an input[type=\'number\'] value to always show 2 decimal places?

Example: I want to see 0.00 instead of

15条回答
  •  攒了一身酷
    2020-11-28 06:35

    This works to enforce a max of 2 decimal places without automatically rounding to 2 places if the user isn't finished typing.

    function naturalRound(e) {
    
       let dec = e.target.value.indexOf(".")
       let tooLong = e.target.value.length > dec + 3
       let invalidNum = isNaN(parseFloat(e.target.value))
    
       if ((dec >= 0 && tooLong) || invalidNum) {
         e.target.value = e.target.value.slice(0, -1)
       }
    }
    

提交回复
热议问题