HTML5 Number Input - Always show 2 decimal places

后端 未结 15 2043
太阳男子
太阳男子 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.

    <input class="my_class_selector" type='number' value='33'/>
    
    
    // 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().

    0 讨论(0)
  • 2020-11-28 06:48

    You can't really, but you a halfway step might be:

    <input type='number' step='0.01' value='0.00' placeholder='0.00' />

    0 讨论(0)
  • 2020-11-28 06:48

    The solutions which use input="number" step="0.01" work great for me in Chrome, however do not work in some browsers, specifically Frontmotion Firefox 35 in my case.. which I must support.

    My solution was to jQuery with Igor Escobar's jQuery Mask plugin, as follows:

    <script src="/your/path/to/jquery-mask.js"></script>
    <script>
        $(document).ready(function () {
            $('.usd_input').mask('00000.00', { reverse: true });
        });
    </script>
    
    <input type="text" autocomplete="off" class="usd_input" name="dollar_amt">
    

    This works well, of course one should check the submitted value afterward :) NOTE, if I did not have to do this for browser compatibility I would use the above answer by @Rich Bradshaw.

    0 讨论(0)
提交回复
热议问题