Click to See Complete Forum and Search --> : Enforce Precision


cmyers
01-20-2003, 02:52 PM
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.

Thank you in advance.

Cathy Myers

khalidali63
01-20-2003, 03:44 PM
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
//your processing
}

for roundup.
Math.round(num);

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

Hope this helps

Khalid

cmyers
01-22-2003, 02:17 PM
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;
}
}