readableNumber function

String readableNumber(
  1. num n, {
  2. int precision = 0,
  3. String unit = '',
  4. bool binary = false,
})

Returns the specified number as a human-readable string.

precision specifies the number of fractional digits to show after the decimal point. precision must be non-negative.

unit, if specified, will be appended to the resulting string.

If binary is true, readableNumber will prefer binary IEC prefixes over SI prefixes. binary will be ignored for numbers with an absolute value less than 1.

Examples:

readableNumber(1, unit: 'B'); // '1 B'
readableNumber(1000); // '1 K'
readableNumber(1234567, precision: 2, unit: 'B'); // '1.23 MB'
readableNumber(1234567, precision: 2, unit: 'B', binary: true); // '1.18 MiB'
readableNumber(0.1, unit: 'g'); // '100 mg'

Implementation

String readableNumber(
  num n, {
  int precision = 0,
  String unit = '',
  bool binary = false,
}) {
  var absoluteValue = n.abs();
  if (absoluteValue > 0 && absoluteValue < 1) {
    return _readableMicroNumber(n, precision: precision, unit: unit);
  }

  var multiplier = binary ? 1024 : 1000;
  var prefixes = binary ? _binaryMacroPrefixes : _siMacroPrefixes;
  var space = ' ';
  var i = 0;
  while (true) {
    if (n.abs() < multiplier) {
      break;
    }
    i += 1;
    if (i == prefixes.length) {
      // Use the largest prefix we have.
      i -= 1;
      break;
    }

    n /= multiplier;
  }

  if (prefixes[i].isEmpty && unit.isEmpty) {
    // Avoid a trailing space.
    space = '';
  }
  return '${n.toStringAsFixed(precision)}$space${prefixes[i]}$unit';
}