user2197806
user2197806

Reputation: 7

Number Restriction after decimal point in javascript

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

Answers (4)

user2197806
user2197806

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

Simon M
Simon M

Reputation: 2941

Try this:

your_number = (your_number).toFixed(3);

Upvotes: 1

Joni
Joni

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

PSR
PSR

Reputation: 40318

You can use toFixed(Your number) for that

Upvotes: 1

Related Questions