« Visualize Science Challenge | Main | Thinking out loud...interviews »

MathExtensions1.0 Errata

The Math.toScientific rounding bug has been resolved, utilizing greenfly's solution

// ############## greenfly's rounding solution ###############
// I left his comments in, but changed the condition to round down
// negative numbers as well, adding a second call to formatDecimals.
// disregard expo_fact - it isn't used here
// ###############################################
// by not dividing by "expo_fact" at the end, we should have the number
// in the desired format: X.XXX, e.g. 3.234
// however, it is possible that by rounding in the step above, we've increased
// the number to XX.XXX, e.g. 9.999999 went to 10.00
// so we need to check for this condition
if (mantissa>=10 || mantissa<=-10) {
mantissa /= 10;
mantissa = Math.formatDecimals(mantissa,sigDigs-1);
exponent++;
}

Updated extensions:

MathExtensions1.1.as

Here is Robert's revised function:

Math.toScientific = function(num,sigDigs) {
    num = Number(num);
    if (isNaN(num)) return num;
    var exponent = Math.floor(Math.log(Math.abs(num))/Math.LN10);
    if (num==0) exponent = 0;
    var tenToPower = Math.pow(10,exponent);
    var mantissa = num/tenToPower;
    mantissa = Math.formatDecimals(mantissa,sigDigs-1);
    if (mantissa>=10 || mantissa<=-10) {
        mantissa /= 10;
        mantissa = Math.formatDecimals(mantissa,sigDigs-1);
        exponent++;
    }
    var output = mantissa;
    if (exponent!=0) {
        output += "e"+exponent;
        return(output);
    }
}; //Robert Penner May 2001 - www.robertpenner.com