magnitude static method

int magnitude(
  1. double x
)

Determines the decimal magnitude of a number. The magnitude is the exponent of the greatest power of 10 which is less than or equal to the number.

@param x the number to find the magnitude of @return the decimal magnitude of x

Implementation

static int magnitude(double x) {
  double xAbs = x.abs();
  double xLog10 = math.log(xAbs) / math.log(10);
  int xMag = xLog10.floor();
  /**
   * Since log computation is inexact, there may be an off-by-one error
   * in the computed magnitude.
   * Following tests that magnitude is correct, and adjusts it if not
   */
  double xApprox = math.pow(10, xMag).toDouble();
  if (xApprox * 10 <= xAbs) xMag += 1;

  return xMag;
}