一旦达到小数点后两位,Javascript 就会限制输入

问题描述 投票:0回答:5

我目前有一个数字输入脚本,其行为类似于计算器,其显示数字的方式类似,但我想在小数点后两个数字之后停止向系列中添加其他数字。

这是我到目前为止所拥有的,尽管限制没有正确发生。

它应该像这样工作:

1.25 - 允许

12.5 - 允许

125.5 - 允许

125.55 - 允许

123.555 - 不允许

rText = document.getElementById("resultText");

function selectNumber(num) {
if (!rText.value || rText.value == "0") {
    rText.value = num;
}
else {

这部分有效...

        rText.value += num;

    }
  }
}

但这部分不起作用...有什么想法吗???

if (rText.value.length - (rText.value.indexOf(".") + 1) > 2) {

        return false;
    } else {
        rText.value += num;

    }
  }
}
javascript decimal-point
5个回答
39
投票

var validate = function(e) {
  var t = e.value;
  e.value = t.indexOf(".") >= 0 ? t.slice(0, t.indexOf(".") + 3) : t;
}
<input type="text" inputmode="numeric" pattern="[0-9+-.]+" id="resultText" oninput="validate(this)" />


4
投票

将先前的值保存在某些数据属性中,如果超过小数点后两位则恢复先前的值

可以使用

Math.round(tis.value*100)/100!=tis.value

检查小数点后两位

注:

即使在复制粘贴场景中,我也使用

oninput
进行验证

function restrict(tis) {
  var prev = tis.getAttribute("data-prev");
  prev = (prev != '') ? prev : '';
  if (Math.round(tis.value*100)/100!=tis.value)
  tis.value=prev;
  tis.setAttribute("data-prev",tis.value)
}
<input type="number" id="rText" oninput="restrict(this);" />


0
投票

我喜欢使用 Math.floor 和 toFixed() 来解决我的小数问题。

这是一个例子:

var value = 123.5555
var roundedNumber = (Math.floor(value * 100) / 100).toFixed(2)

roundedNumber 将是字符串形式的“123.55”。因此,如果您想要一个数字,只需添加:

var value = 123.5555
var roundedNumber = Number((Math.floor(value * 100) / 100).toFixed(2))

现在你的值是一个数字,并固定到小数点后两位。


0
投票

只需复制粘贴此方法,然后在您必须检查此十进制验证的相应按钮上调用此方法。

function CheckDecimal(inputtxt)   
  {   
  var decimal=  /^[-+]?[0-9]+\.[0-9]+$/;   
  if(inputtxt.value.match(decimal))   
    {   
    alert('Correct, try another...')  
    return true;  
    }  
  else  
    {   
    alert('Wrong...!')  
    return false;  
    }  
  }

0
投票
Java script way  :

    (isNaN(value)) <-- First to check the input value is number

    
    After verifying the value input is numeric, check the value should have only two decimal values after this, also allow single value to pass

    function checkDecimal(value)   
    {  
        var split = value.split('.');
        console.log(split);
        if (split.length === 2 && split[1].length > 2) {
            console.log(split[1].length);
            return false;
        }
        return true;
    }
© www.soinside.com 2019 - 2024. All rights reserved.