[英]How to Make Input Only Allow Two Decimal Places to be Entered?
I am not sure how to do this, but I believe it can be done with JavaScript, or PHP. 我不知道如何做到这一点,但我相信它可以用JavaScript或PHP完成。 Is there anyway I can make an input that only allows 2 decimal places to be entered? 无论如何我可以输入只允许输入2位小数? Essentially, I would like the input to stop entering numbers after two decimal places, rather than give an error if five have been entered. 基本上,我希望输入在两位小数后停止输入数字,而不是在输入五位时给出错误。
I am not looking for a validator, but rather an inhibitor to block anything being inputted that is more than 2 decimal places. 我不是在寻找一个验证器,而是一个阻止器来阻止任何输入超过2位小数的东西。
If anyone knows how to do this or can provide any help it will be greatly appreciated. 如果有人知道如何做到这一点或可以提供任何帮助,将不胜感激。 Thank you for any help. 感谢您的任何帮助。
If this is a prevention then I would do it in the php as you can pretty much always find a way around preventions in javascript. 如果这是一个预防,那么我会在PHP中这样做,因为你几乎总能在javascript中找到预防方法。
Maybe combine it with a Javascript function as well so users get formatting help and have this as a definitive prevention? 也许将它与Javascript函数结合使用,以便用户获得格式化帮助并将其作为明确的预防措施?
To do this in php you can use the number_float()
function: 要在php中执行此操作,您可以使用number_float()
函数:
$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00
First, write a trimming function 首先,编写修剪功能
function trimDP(x, dp) {
if (dp === 0)
return Math.floor(+x).toString();
dp = Math.pow(10, dp || 2);
return (Math.floor((+x) * dp) / dp).toString();
}
// ex.
trimDP("1.2345"); // "1.23"
Next, set up this trimming function to be applied on keypress and onchange to your <input>
eg by giving them the class token dp2
接下来,设置此剪裁功能要对按键应用, 平变化到你<input>
例如,通过给予他们一流的令牌dp2
<input type="text" value="0" class="dp2" />
(function () { // do this after nodes loaded
var nodes = document.querySelectorAll('.dp2'), i;
function press(e) {
var s = String.fromCharCode(e.keyCode);
if (s === '.')
if (this.value.indexOf('.') === -1)
return; // permit typing `.`
this.value = trimDP(this.value + s);
e.preventDefault();
};
function change() {
this.value = trimDP(this.value);
}
for (i = 0; i < nodes.length; ++i) {
nodes[i].addEventListener('keypress', press);
nodes[i].addEventListener('change', change);
}
}());
You may also want to prevent non-numeric keys 您可能还想要阻止非数字键
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.