Go: 将 byte 字节转为 KB / MB / GB 单位

Go: Format byte size to human readable format

在 Go 语言中, 经常需要将字节数 (byte) 转换为更加直观、易读的字符串形式, 例如将文件大小或内存占用显示为 KBMBGB 等。

常见的转换方式主要有两种标准:

  • 十进制 (SI 标准): 以 1000 为单位 (kB、MB、GB)
  • 二进制 (IEC 标准): 以 1024 为单位 (KiB、MiB、GiB)

十进制 (SI) 格式化函数

使用 1000 作为单位, 常见于硬盘容量、网络带宽等场景

func ByteCountDecimal(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])
}

二进制 (IEC) 格式化函数

使用 1024 作为单位, 更符合操作系统、内存、文件系统的实际计算方式

func ByteCountBinary(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])
}

示例输入与输出对照

           Input     Decimal (SI)     Binary (IEC)
               0            "0 B"            "0 B"
              27           "27 B"           "27 B"
             999          "999 B"          "999 B"
            1000         "1.0 kB"         "1000 B"
            1023         "1.0 kB"         "1023 B"
            1024         "1.0 kB"        "1.0 KiB"
            1728         "1.7 kB"        "1.7 KiB"
   1855425871872         "1.9 TB"        "1.7 TiB"
   math.MaxInt64         "9.2 EB"        "8.0 EiB"

原文

Go: Format byte size to human readable format

最后更新于 2025-12-28