Question

I am not sure how to do this, but I believe it can be done with JavaScript, or PHP. Is there anyway I can make an input that only allows 2 decimal places to be entered? 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.

If anyone knows how to do this or can provide any help it will be greatly appreciated. Thank you for any help.

Was it helpful?

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

DEMO

OTHER TIPS

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 the number_float() function:

$foo = "105";

echo number_format((float)$foo, 2, '.', '');  // Outputs -> 105.00

PHP: show a number to 2 decimal places

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top