How to format byte size as kilobytes, megabytes in Go

Created
Modified

Get file size in human-readable units like kilobytes (KB), Megabytes (MB) or GigaBytes (GB)

SI (Decimal 1 k = 1,000)

A metric prefix is a unit prefix that precedes a basic unit of measure to indicate a multiple or submultiple of the unit. List of SI prefixes: k、M、G、T、P、E、Z、Y.

package main

import (
  "fmt"
  "math"
)

func FormatByteSI(b int64) string {

  const unit = 1000
  if b < unit {
    return fmt.Sprintf("%d B", b)
  }
  div, exp := int64(unit), 0
  for n := b / unit; n >= unit; n /= unit {
    div *= unit
    exp++
  }
  return fmt.Sprintf("%.1f %cB",
    float64(b)/float64(div), "kMGTPE"[exp])
}

func main() {

  FormatByteSI(800) // 800 B
  FormatByteSI(1024) // 1.0 kB
  FormatByteSI(987654321) // 987.7 MB
  FormatByteSI(1551859712) // 1.6 GB
  FormatByteSI(math.MaxInt64) // 9.2 EB

}
800 B
1.0 kB
987.7 MB
1.6 GB
9.2 EB

IEC (binary 1 Ki = 1,024)

A binary prefix is a unit prefix for multiples of units in data processing, data transmission, and digital information, principally in association with the bit and the byte, to indicate multiplication by a power of 2. List of SI prefixes: Ki、Mi、Gi、Ti、Pi、Ei、Zi、Yi.

package main

import (
  "fmt"
  "math"
)

func FormatByteIEC(b int64) string {

  const unit = 1024
  if b < unit {
    return fmt.Sprintf("%d B", b)
  }
  div, exp := int64(unit), 0
  for n := b / unit; n >= unit; n /= unit {
    div *= unit
    exp++
  }
  return fmt.Sprintf("%.1f %ciB",
    float64(b)/float64(div), "KMGTPE"[exp])
}

func main() {

  FormatByteIEC(800)           // 800 B
  FormatByteIEC(1024)          // 1.0 KiB
  FormatByteIEC(987654321)     // 941.9 MiB
  FormatByteIEC(1551859712)    // 1.4 GiB
  FormatByteIEC(math.MaxInt64) // 8.0 EiB

}
800 B
1.0 KiB
941.9 MiB
1.4 GiB
8.0 EiB

Convert File Size

files, err := ioutil.ReadDir(".")
if err != nil {
  // panic()
}

for _, file := range files {
  fmt.Printf("%-6d %-6s %-6s\n", file.Size(), FormatByteSI(file.Size()), FormatByteIEC(file.Size()))
}
963  963 B  963 B 
2197 2.2 kB 2.1 KiB
1172 1.2 kB 1.1 KiB
384  384 B  384 B 
1165 1.2 kB 1.1 KiB
753  753 B  753 B 

Related Tags