d
Amit DhamuSoftware Engineer
 

Human friendly file size

1 minute read 00000 views

Method 1

const filesize = (size: number) => {
  const threshold = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']

  let bytes = Math.abs(size)

  let i = 0
  while (bytes >= threshold) {
    bytes /= threshold
    i += 1
  }

  return `${bytes.toFixed(2)} ${sizes.at(i)}`
}

Method 2

const filesize = (size: number) => {
  const threshold = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']

  const i = Math.floor(Math.log(size) / Math.log(threshold))

  return `${((size / threshold ** i) * 1).toFixed(2)} ${sizes.at(i)}`
}