📚Cheatsheets

Cheatsheet collection for go, rust, python, shell and javascript.

Convert byte size to human readable format in Golang

Golang: Format byte size to human readable text.

import "fmt"

var sizes = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB"}

func FormatFileSize(s float64, base float64) string {
	unitsLimit := len(sizes)
	i := 0
	for s >= base && i < unitsLimit {
		s = s / base
		i++
	}

	f := "%.0f %s"
	if i > 1 {
		f = "%.2f %s"
	}

	return fmt.Sprintf(f, s, sizes[i])
}

How to use:

var size = 452984832
fmt.Printf("%s\n", FormatFileSize(float64(size), 1024.0)) // 432.00 MB

Run it here