-
Notifications
You must be signed in to change notification settings - Fork 7
Open
Labels
Description
For numerical readout and numbers that shows up in panels, space is often at a premium and the dynamical range of the numbers to be displayed can be very large. Without resorting to scientific notation, it is difficult to display large number with a fixed number of decimal places. The proposal is to have method that lives in DOT/Util that would be able to round the numbers with a maximum number of decimal places (rather than a fixed number number of decimal places). In this way large number can still be displayed without occupying too much real estate. See examples in the code below.
A (local) version of this algorithm was used in charges and fields, and least squares regression.
/**
* Decimal adjustment of a number.
* Function that returns (for numbers smaller than ten) a number (as a string) with a fixed number of decimal places
* whereas for numbers larger than ten, the number/string is returned a fixed number of significant figures that
* is at least equal to the number of decimal places (or larger)
*
* @param {number} number
* @param {Object} [options]
* @returns {string}
*/
function decimalAdjust( number, options ) {
options = _.extend( {
maxDecimalPlaces: 3
}, options );
// e.g. for maxDecimalPlaces: 3
// 9999.11 -> 9999 (numbers larger than 10^maxDecimalPlaces) are rounded to unity
// 999.111 -> 999.1
// 99.1111 -> 99.11
// 9.11111 -> 9.111
// 1.11111 -> 1.111
// 0.11111 -> 0.111
// 0.01111 -> 0.011
// 0.00111 -> 0.001
// 0.00011 -> 0.000
// number = mantissa times 10^(exponent) where the mantissa is between 1 and 10 (or -1 to -10)
var exponent = Math.floor( Math.log10( Math.abs( number ) ) );
var decimalPlaces;
if ( exponent >= options.maxDecimalPlaces ) {
decimalPlaces = 0;
}
else if ( exponent > 0 ) {
decimalPlaces = options.maxDecimalPlaces - exponent;
}
else {
decimalPlaces = options.maxDecimalPlaces;
}
return Util.toFixed( number, decimalPlaces );
}