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


Answers:



60

您不能真正做到,但您可能需要做的一半:

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


16
这在Chrome 55.0.2883.75中不起作用。如果我创建一个表单元素,则将标记放在其内部上方,在输入中键入“ 1200”,然后单击选项卡,使其远离元素,显示的文本仍为“ 1200”而不是“ 1200.00”。
里克·格洛斯

8
这似乎只是控制步箭头的作用。设置值1/3不会将结果限制为两位小数
Sonic Soul

它不适用于Chrome版本78.0.3904.108(正式版本)(64位)
Fasco

13

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

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


7
对我不起作用。如果我单击向上至5.01,然后向下单击,则在Chrome 72中显示5而不是5.00
gman

如果要查找严格的数字解释,则这是正确的行为,“ 5.00”是字符串。
持不同政见者愤怒

1
不相关的。问题是希望始终显示2个小数位,而这个答案不能做到这一点。
gman

然后,他们正在寻找input[type="text"]带有完全重新实现的所有本机铃声input[type="number"],或者将这个字段换成另一个以根据元素状态显示值。
持不同政见者愤怒

8

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

我的解决方案是使用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">

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


2
不知道为什么这被否决了..令我惊讶的是。就像我在回答中所说的那样,这是仅对于那些像我一样坚持支持其他答案不起作用的浏览器的人的替代解决方案。而且我知道它可行,因为它目前正在生产和运行中!
little_birdie

在这种情况下,JavaScript应该是后备而非默认行为。如果该功能不存在,则将Javascript挂钩是合适的。您可以通过测试输入的type属性是否为number或来进行检查text。如果text即使HTML是这样编写的,也返回它,number则表明浏览器不支持该类型,将这种行为挂接到它上是适当的操作。
异议人士之怒

如果您在评论中指出,我会修改我的回答以包含该功能。如今,大多数应用程序在没有js ..的情况下根本无法工作,或者几乎没有工作..因此,它变得毫无意义。但我同意支票可以改善答案。我目前正在旅行..我回来时会修改它。
little_birdie

5

基于,从@Guilherme费雷拉回答您可以触发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" />


这仅在元素失去焦点时有效。如果用户在填写输入字段后立即单击“提交”按钮,则不会看到可能会误导用户的更正值。
新手合计

我不确定100%,但是我认为该change()功能将在用户输入和提交按钮单击之间的短时间内触发。因此,这应该不是问题。
mhellmeier

是的,它确实的确发生了变化,但是用户不会知道,因此可能会导致混乱,因为用户在立即提交校正后的值之前将看不到它。虽然这可能不是最usecases一个问题
总新手

3

如果用户没有完成输入操作,这将强制执行最多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)
   }
}

3

如果您登陆这里,只是想知道如何限制到2个小数位,我有一个本地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:

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

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


1

我知道这是一个古老的问题,但是在我看来,这些答案似乎都无法回答所提出的问题,因此希望这对以后的人有所帮助。

是的,您始终可以显示2个小数位,但是不幸的是,仅靠元素属性不能做到这一点,您必须使用JavaScript。

我应该指出,这对于大数字而言并不理想,因为它将始终强制尾随零,因此用户将不得不向后移动光标,而不是删除字符以设置大于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" />


1

这是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));
}

缺点:每次输入数字更改以重新格式化时,都必须调用此方法。

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

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


0

我的首选方法是使用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

})

0

最佳答案为我提供了解决方案,但我不喜欢立即更改用户输入,因此我增加了延迟,我认为这有助于改善用户体验

var delayTimer;
function input(ele) {
    clearTimeout(delayTimer);
    delayTimer = setTimeout(function() {
       ele.value = parseFloat(ele.value).toFixed(2).toString();
    }, 800); 
}
<input type='number' oninput='input(this)'>

https://jsfiddle.net/908rLhek/1/


-1
import { Component, Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'replace'
})

export class ReplacePipe implements PipeTransform {
    transform(value: any): any {
        value = String(value).toString();
        var afterPoint = '';
        var plus = ',00';
        if (value.length >= 4) {
            if (value.indexOf('.') > 0) {
                afterPoint = value.substring(value.indexOf('.'), value.length);
                var te = afterPoint.substring(0, 3);
                if (te.length == 2) {
                    te = te + '0';
                }
            }
            if (value.indexOf('.') > 0) {
                if (value.indexOf('-') == 0) {
                    value = parseInt(value);
                    if (value == 0) {
                        value = '-' + value + te;
                        value = value.toString();
                    }
                    else {
                        value = value + te;
                        value = value.toString();
                    }
                }
                else {
                    value = parseInt(value);
                    value = value + te;
                    value = value.toString();
                }
            }
            else {
                value = value.toString() + plus;
            }
            var lastTwo = value.substring(value.length - 2);
            var otherNumbers = value.substring(0, value.length - 3);
            if (otherNumbers != '')
                lastTwo = ',' + lastTwo;
            let newValue = otherNumbers.replace(/\B(?=(\d{3})+(?!\d))/g, ".") + lastTwo;
            parseFloat(newValue);
            return `${newValue}`;
        }
}
}

你可以试试这个管道
RamakanthReddy Kowdampalli


-3

看看这个

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

5
可以步进,但不能格式化。如果要保留小数点后两位,并且有人输入(或旋转到)“ 0.1”,则在所有浏览器中它将保留为“ 0.1”(而不是所需的“ 0.01”)。占位符仅适用于空条件(也不是格式)
MC9000

-3

这是正确的答案:

<input type="number" step="0.01" min="-9999999999.99" max="9999999999.99"/>


4
这是一种更好,更现代的方法,许多其他答案也可以,但仍不会在输入的内容上加上尾随的零
pcnate
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.