/* This source file will contain a function used to display a number
 * to a given number of significant figures
 */

function round_sig(num, digits)
{
    //this function will tidy a number, display the number
    //of significant figures as indicated by the parameter
    //digits

    //check to make sure that this is a number
    var test = new Number(num);
    if(test == Number.NaN) { //not a number
        alert(num + " is not a number");
        return num;
    }
 
    //return if zero or one
    if(num == 0.0) {
        return 0.0;
    }

    //convert to exponential - of the format X.XXXe+XX
    var power = Math.floor((Math.log(Math.abs(num))/Math.log(10.0)));
    var mantissa = num/Math.pow(10.0, power);

    //get the correct number of significant figures in the mantissa
    var divisor = Math.pow(10.0, digits - 1);

    if((power < -3) || (power > digits)){ //display as exponential
        var sign = "";
        if(power > 0) {
            sign = "+";
        }

        tidy = Math.round(mantissa*divisor)/divisor + "e" + sign
            + power;
    }
    else {
       tidy = (Math.round(mantissa*divisor) * Math.pow(10, power))/divisor;

        if(Math.abs(tidy) < 1) {
            //need to to some manipulation here
            var manip = new String(tidy);

            //get the significant figures
            var index = manip.indexOf(".") + 1;
            var count = 0;
            while(manip.substring(index, index+1) == "0") {
                index++;
                count++;

                if(count > 10) {
                    break;
                }
            }

            tidy = manip.substring(0,Math.min(index+digits, 
                                      manip.length));
        }
    } 
    return tidy;
}