Reputation: 7
How to restrict the number of digits after the decimal point using "onkeyup" even in javascript?
I want to restrict the number of digits after the decimal point based on an input already given in the page. if i give the input as 3 then the digits after the decimal points should be only 3. for this i need to use javascript so that at runtime itself output is shown to user and the user should not be able to enter more than 3.
Upvotes: 0
Views: 905
Reputation: 7
The objectvalue is the current inputtext object where value is entered. id is the object value of the field where precision(no of digits after decimal) is entered.
function decimalRestriction(objectValue,id) { var precision=document.getElementById(id).value; var value=objectValue.value; if(value.match('.')) { var decimaldigits=value.split('.'); if(decimaldigits[1].length > precision) objectValue.value= decimaldigits[0]+ '.' + decimaldigits[1].substring(0, precision); } }
Upvotes: 0
Reputation: 111219
You can use the toFixed
method:
var withDecimals = (1*value).toFixed(numberOfDecimals);
Multiplying by 1 makes sure that we are dealing with a number and not some other object, like a string.
Upvotes: 2