dcsimg
www.webdeveloper.com
Results 1 to 3 of 3

Thread: Enforce Precision

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

    Question 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.

    Thank you in advance.

    Cathy Myers

  2. #2
    Join Date
    Dec 2002
    Location
    Calgary, Canada
    Posts
    2,653
    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/m...jsref/math.htm

    Hope this helps

    Khalid

  3. #3
    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;
    }
    }

Thread Information

Users Browsing this Thread

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
  •  
HTML5 Development Center



Recent Articles