HTML5 Number Input - Always show 2 decimal places

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

    This is a quick formatter in JQuery using the .toFixed(2) function for two decimal places.

    
    
    
    // if this first call is in $(document).ready() it will run
    // after the page is loaded and format any of these inputs
    
    $(".my_class_selector").each(format_2_dec);
    function format_2_dec() {
        var curr_val = parseFloat($(this).val());
        $(this).val(curr_val.toFixed(2));
    }
    

    Cons: you have to call this every time the input number is changed to reformat it.

    // listener for input being changed
    $(".my_class_selector").change(function() {
        // potential code wanted after a change
    
        // now reformat it to two decimal places
        $(".my_class_selector").each(format_2_dec);
    });
    

    Note: for some reason even if an input is of type 'number' the jQuery val() returns a string. Hence the parseFloat().

提交回复
热议问题