HTML5 Number Input - Always show 2 decimal places

后端 未结 15 2097
太阳男子
太阳男子 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:41

    I know this is an old question, but it seems to me that none of these answers seem to answer the question being asked so hopefully this will help someone in the future.

    Yes you can always show 2 decimal places, but unfortunately it can't be done with the element attributes alone, you have to use JavaScript.

    I should point out this isn't ideal for large numbers as it will always force the trailing zeros, so the user will have to move the cursor back instead of deleting characters to set a value greater than 9.99

    //Use keyup to capture user input & mouse up to catch when user is changing the value with the arrows
        $('.trailing-decimal-input').on('keyup mouseup', function (e) {
    
            // on keyup check for backspace & delete, to allow user to clear the input as required
            var key = e.keyCode || e.charCode;
            if (key == 8 || key == 46) {
                return false;
            };
    
            // get the current input value
            let correctValue = $(this).val().toString();
    
             //if there is no decimal places add trailing zeros
            if (correctValue.indexOf('.') === -1) {
                correctValue += '.00';
            }
    
            else {
    
                //if there is only one number after the decimal add a trailing zero
                if (correctValue.toString().split(".")[1].length === 1) {
                    correctValue += '0'
                }
    
                //if there is more than 2 decimal places round backdown to 2
                if (correctValue.toString().split(".")[1].length > 2) {
                    correctValue = parseFloat($(this).val()).toFixed(2).toString();
                }
            }
    
            //update the value of the input with our conditions
            $(this).val(correctValue);
        });
    
    

提交回复
热议问题