toHumanReadableByteCount static method

String toHumanReadableByteCount(
  1. int bytes, {
  2. bool binarySystem = true,
  3. bool rightNotation = false,
  4. int decimals = 2,
})

@param bytes the amount of bytes to convert @param binarySystem true means to convert using Binary System (divide by 1024), false means International System (divide by 1000) @param rightNotation true means to show KiB, MiB, GiB, etc if system is false. false means to show kB, MB, GB, etc whatever value system is. @param decimals amount of decimals after float point @return

Implementation

static String toHumanReadableByteCount(int bytes,
    {bool binarySystem = true,
    bool rightNotation = false,
    int decimals = 2}) {
  int unit = binarySystem ? 1024 : 1000;
  if (bytes < unit) return '$bytes B';
  int exp = (Math.log(bytes) / Math.log(unit)).truncate();
  String pre = (binarySystem ? 'kMGTPEZY' : 'KMGTPEZY')[exp - 1] +
      (rightNotation ? (binarySystem ? 'i' : '') : '');
  if (!rightNotation) pre = pre.toUpperCase();
  String decimalsParam = '';
  if (decimals > 0) decimalsParam = '0.';
  while (decimals-- > 0) {
    decimalsParam += '0';
  }
  return Intl.NumberFormat('#$decimalsParam ${pre}B', 'en_US')
      .format(bytes / Math.pow(unit, exp));
}