Javascript restrict input once 2 decimal places have been reached

cloudseeker picture cloudseeker · Sep 20, 2017 · Viewed 14.5k times · Source

I currently have a number input script that behaves similar to a calculator with the way numbers are displayed, but I want to stop the adding of additional numbers to the series after two numbers past the decimal point.

Here is what I have so far, though the limiting doesn't occur correctly.

It should work like this:

1.25 - Allowed

12.5 - Allowed

125.5 - Allowed

125.55 - Allowed

123.555 - Not Allowed

rText = document.getElementById("resultText");

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

this part works...

        rText.value += num;

    }
  }
}

but this part doesn't work... Any ideas???

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

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

    }
  }
}

Answer

Brahma Dev picture Brahma Dev · Sep 20, 2017

var validate = function(e) {
  var t = e.value;
  e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
<input type="text" id="resultText" oninput="validate(this)" />