Typescript - Human Readable File Sizes

Article Information

Article Content

This is a stupid simple function that we discovered some short time ago and now gets copied anytime we need to work with files. Hate that we used to jump through hoops to do this with messy if's.

// #region formatBytes
/**
 * Get bytes in human readable format
 * @param bytes bytes to format
 * @returns Formatted bytes string
 */
public formatBytes(bytes: number): string {
  if (bytes <= 0) return "0 B";
  const sizes = ["B", "KB", "MB", "GB"];
  const lScale = Math.floor(Math.log(bytes) / Math.log(1024));
  const result = bytes / Math.pow(1024, lScale);
  if (result < 10) {
    return `${result.toFixed(1)} ${sizes[lScale]}`;
  }
  return `${result.toFixed(0)} ${sizes[lScale]}`;
}
// #endregion formatBytes

Our Mission

At Wildlink, our mission is to deliver the best business solutions we can to enable our clients to gather and unlock the answers in their data.
We are committed to fostering long-term partnerships built on trust, integrity, and a relentless pursuit of innovation.