1. Registered User
Join Date
Jan 2003
Location
Miamisburg, Ohio
Posts
6

## Enforce Precision

I am a JS newbie and have received my first task. I need to write a function that will enforce precision.

I will need to test for NAN. If it's a string, I will need to convert it to a number and then enforce the precision to two decimals places.

Does anyone have a similiar script I can take a look at? Or any suggestions for me?

In addition, I will then need to round up.

Cathy Myers

2. You might want to try something like this

if(!isNaN(str){
//str is a number
//convert it to number
/for integer
var iStr = parseInt(str);
//for float
fStr = parseFloat(str);
}else{//not a number
}

for roundup.
Math.round(num);

Look at the documents for JavaScript Math object.
at
http://developer.netscape.com/docs/m...jsref/math.htm

Hope this helps

Khalid

3. Registered User
Join Date
Jan 2003
Location
Miamisburg, Ohio
Posts
6
Khalid,
Thank you for your suggestions, it got me started. The final function looks like this:

function enforcePrecision(sValue, iPrecision, sDirection){
fValue = parseFloat(sValue); //Convert to number
if(!isNAN(value)){
var sPrecision = "1"
for(var i=0; i < iPrecision-1; i++){
sPrecision += "0"
}
iPrecision = parseInt(sPrecision);
fValue *= iPrecision; //Multiply by value
eval(value);

if(!sDirection){
fValue = Math.round(fValue); //Undefined direction
}
if(sDirection == "Down"){
fValue = Math.floor(fValue); //Round down
else
fValue = Math.ceil(fValue); //Round up
}
value /= iPrecision;
return value;
}
}

There are currently 1 users browsing this thread. (0 members and 1 guests)

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•