0

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.

Kelsey
  • 913
  • 3
  • 19
  • 41

2 Answers2

1

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

Community
  • 1
  • 1
Dan
  • 11,914
  • 14
  • 49
  • 112
  • I need it to format while it is being inputted, not after the input has been made submitted. Thank you, though. – Kelsey Apr 10 '14 at 17:33
  • Okay, just remember if it's a form input then I can turn javascript off and just submit any number and it will not be prevented unless you have php validation. – Dan Apr 10 '14 at 17:40
1

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

Paul S.
  • 64,864
  • 9
  • 122
  • 138