Html HTML5 数字输入 - 始终显示 2 个小数位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22641074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:22:12  来源:igfitidea点击:

HTML5 Number Input - Always show 2 decimal places

html

提问by Guilherme Ferreira

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

有什么方法可以将input[type='number']值格式化为始终显示 2 个小数位?

Example: I want to see 0.00instead of 0.

示例:我想查看0.00而不是0.

采纳答案by Guilherme Ferreira

Solved following the suggestions and adding a piece of jQuery to force the format on integers:

解决了以下建议并添加了一段 jQuery 以强制使用整数格式:

parseFloat($(this).val()).toFixed(2)

回答by Rich Bradshaw

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

你真的不能,但你的中间步骤可能是:

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

回答by Dissident Rage

Using the stepattribute will enable it. It not only determines how much it's supposed to cycle, but the allowable numbers, as well. Using step="0.01"shoulddo the trick but this may depend on how the browser adheres to the standard.

使用该step属性将启用它。它不仅决定了它应该循环多少,而且还决定了允许的数量。使用step="0.01"应该可以解决问题,但这可能取决于浏览器如何遵守标准。

<input type='number' step='0.01' value='5.00'>

回答by little_birdie

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.

input="number"step="0.01"在 Chrome 中使用的解决方案对我很有用,但是在某些浏览器中不起作用,特别是在我的情况下 Frontmotion Firefox 35..我必须支持。

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

我的解决方案是使用 Igor Escobar 的 jQuery Mask 插件来 jQuery,如下所示:

<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.

这很有效,当然应该在之后检查提交的值:) 注意,如果我不必为了浏览器兼容性而这样做,我将使用@Rich Bradshaw 的上述答案。

回答by SuperCodeBrah

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

如果用户没有完成输入,这可以强制最多保留 2 位小数,而不会自动四舍五入到 2 位。

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)
   }
}

回答by mhellmeier

Based on thisanswer from @Guilherme Ferreira you can trigger the parseFloatmethod every time the field changes. Therefore the value always shows two decimal places, even if a user changes the value by manual typing a number.

根据@Guilherme Ferreira 的这个答案,您可以在parseFloat每次字段更改时触发该方法。因此,该值始终显示两位小数,即使用户通过手动键入数字来更改该值。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(".floatNumberField").change(function() {
            $(this).val(parseFloat($(this).val()).toFixed(2));
        });
    });
</script>

<input type="number" class="floatNumberField" value="0.00" placeholder="0.00" step="0.01" />

回答by Stephen Paul

If you landed here just wondering how to limit to 2 decimal placesI have a native javascript solution:

如果您来到这里只是想知道如何限制为 2 个小数位,我有一个本机 javascript 解决方案:

Javascript:

Javascript:

function limitDecimalPlaces(e, count) {
  if (e.target.value.indexOf('.') == -1) { return; }
  if ((e.target.value.length - e.target.value.indexOf('.')) > count) {
    e.target.value = parseFloat(e.target.value).toFixed(count);
  }
}

HTML:

HTML:

<input type="number" oninput="limitDecimalPlaces(event, 2)" />


Note that this cannot AFAIK, defend against thischrome bug with the number input.

请注意,这不能 AFAIK,请使用数字输入来防御chrome 错误。

回答by kblocks

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

这是 JQuery 中使用.toFixed(2)保留两位小数的函数的快速格式化程序。

<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().

注意:出于某种原因,即使输入是“数字”类型,jQuery 也会val()返回一个字符串。因此parseFloat()

回答by nikk wong

My preferred approach, which uses dataattributes to hold the state of the number:

我的首选方法,它使用data属性来保存数字的状态:

<input type='number' step='0.01'/>

// react to stepping in UI
el.addEventListener('onchange', ev => ev.target.dataset.val = ev.target.value * 100)

// react to keys
el.addEventListener('onkeyup', ev => {

    // user cleared field
    if (!ev.target.value) ev.target.dataset.val = ''

    // non num input
    if (isNaN(ev.key)) {

        // deleting
        if (ev.keyCode == 8)

            ev.target.dataset.val = ev.target.dataset.val.slice(0, -1)

    // num input
    } else ev.target.dataset.val += ev.key

    ev.target.value = parseFloat(ev.target.dataset.val) / 100

})

回答by Verno

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.

是的,您始终可以显示 2 个小数位,但不幸的是,仅凭元素属性无法做到这一点,您必须使用 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

我应该指出这对于大数字并不理想,因为它总是会强制尾随零,因此用户必须将光标移回而不是删除字符以设置大于 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);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="my-number-input" class="form-control trailing-decimal-input" type="number" min="0.01" step="0.01" value="0.00" />