dataSizeFormat function

String? dataSizeFormat(
  1. int? size, {
  2. bool? decimalBase,
  3. bool? binaryBase,
})

Formats size as a data format using binary of decimal base for sufixes.

  • Decimal base: bytes, KB, MB and GB.
  • Binary base: bytes, KiB, MiB and GiB.

decimalBase Default true. If true uses a decimal base, if false uses decimal base.

binaryBase Default false. If true uses a binary base, if false uses decimal base.

Implementation

String? dataSizeFormat(int? size, {bool? decimalBase, bool? binaryBase}) {
  if (size == null) return null;

  bool? baseDecimal;

  if (decimalBase != null) {
    baseDecimal = decimalBase;
  }

  if (binaryBase != null) {
    if (baseDecimal == null) {
      baseDecimal = !binaryBase;
    } else if (baseDecimal) {
      baseDecimal = true;
    } else {
      baseDecimal = !binaryBase;
    }
  }

  baseDecimal ??= true;

  if (baseDecimal) {
    if (size < 1000) {
      return '$size bytes';
    } else if (size < 1000 * 1000) {
      var s = '${size ~/ 1000} KB';
      return s;
    } else if (size < 1000 * 1000 * 1000) {
      return '${formatDecimal(size / (1000 * 1000))!} MB';
    } else {
      return '${formatDecimal(size / (1000 * 1000 * 1000))!} GB';
    }
  } else {
    if (size < 1024) {
      return '$size bytes';
    } else if (size < 1024 * 1024) {
      var s = '${size ~/ 1024} KiB';
      return s;
    } else if (size < 1024 * 1024 * 1024) {
      return '${formatDecimal(size / (1024 * 1024))!} MiB';
    } else {
      return '${formatDecimal(size / (1024 * 1024 * 1024))!} GiB';
    }
  }
}