toStringAsPrecision method

String toStringAsPrecision(
  1. int precision
)

A string representation with precision significant digits.

Implementation

String toStringAsPrecision(int precision) {
  assert(precision > 0);

  if (this == zero) {
    return <String>[
      '0',
      if (precision > 1) '.',
      for (var i = 1; i < precision; i++) '0',
    ].join();
  }

  final limit = ten.pow(precision).toDecimal();

  var shift = one;
  final absValue = abs();
  var pad = 0;
  while (absValue * shift < limit) {
    pad++;
    shift *= ten;
  }
  while (absValue * shift >= limit) {
    pad--;
    shift = (shift / ten).toDecimal();
  }
  final value = ((this * shift).round() / shift).toDecimal();
  return pad <= 0 ? value.toString() : value.toStringAsFixed(pad);
}