formatNumber static method

String formatNumber(
  1. double value,
  2. int maxDecimals
)

Implementation

static String formatNumber(double value, int maxDecimals) {
  double v = value;
  if ( false == (value == value) ) {
    return "NaN";
  }
  if ( v == 0.0 ) {
    return "0";
  }
  if ( value * 0.5 == value ) {
    if ( value > 0.0 ) {
      return "Infinity";
    }
    return "-Infinity";
  }
  bool neg = false;
  if ( v < 0.0 ) {
    neg = true;
    v = 0.0 - v;
  }
  if ( v >= 1000000000.0 ) {
    double place = 1.0;
    while (v / place >= 10.0) {
      place = place * 10.0;
    }
    String big = "";
    double rest = v;
    while (place >= 1.0) {
      big = big + VlJson.digitChar(VlJson.digitAt(rest, place));
      rest = rest - VlJson.digitAt(rest, place).toDouble() * place;
      place = place / 10.0;
    }
    String tail = VlJson.fractionDigits(rest, maxDecimals);
    if ( tail.length > 0 ) {
      big = (big + ".") + tail;
    }
    if ( neg ) {
      return "-" + big;
    }
    return big;
  }
  double scale = 1.0;
  int k = 0;
  while (k < maxDecimals) {
    scale = scale * 10.0;
    k = k + 1;
  }
  int whole = (v).floor();
  double frac = v - whole.toDouble();
  if ( frac == 0.0 ) {
    if ( neg ) {
      return "-" + VlJson.intToText(whole);
    }
    return VlJson.intToText(whole);
  }
  double units = frac * scale + 0.5;
  if ( false == (units < scale) ) {
    whole = whole + 1;
    units = 0.0;
  }
  String out = VlJson.intToText(whole);
  String fracText = "";
  double place_1 = scale;
  double rest_1 = units;
  int i = 0;
  while (i < maxDecimals) {
    place_1 = place_1 / 10.0;
    int digit = (rest_1 / place_1).floor();
    rest_1 = rest_1 - digit.toDouble() * place_1;
    fracText = fracText + VlJson.digitChar(digit);
    i = i + 1;
  }
  int end = fracText.length;
  bool stop = false;
  while (end > 0 && false == stop) {
    if ( fracText.codeUnitAt(end - 1) == 48 ) {
      end = end - 1;
    } else {
      stop = true;
    }
  }
  if ( end > 0 ) {
    out = (out + ".") + fracText.substring(0, end );
  }
  if ( neg ) {
    return "-" + out;
  }
  return out;
}