javascript - How to Make Input Only Allow Two Decimal Places to be Entered?
Get the solution ↓↓↓Solution:
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>
e.g. by giving them the class tokendp2
<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
Answer
Solution:
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.
Maybe combine it with a Javascript function as well so users get formatting help and have this as a definitive prevention?
To do this in php you can use thenumber_float()
function:
$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.