How to format bytes to kilobytes, megabytes, gigabytes and terabytes in Go

1 Answer

0 votes
package main

import (
	"fmt"
)

func main() {
	fmt.Println(FormatBytes(9823453784599))
	fmt.Println(FormatBytes(7124362542))
	fmt.Println(FormatBytes(23746178))
	fmt.Println(FormatBytes(1048576))
	fmt.Println(FormatBytes(1024000))
	fmt.Println(FormatBytes(873445))
	fmt.Println(FormatBytes(1024))
	fmt.Println(FormatBytes(978))
	fmt.Println(FormatBytes(13))
	fmt.Println(FormatBytes(0))
}

func FormatBytes(bytes int64) string {
	sizes := []string{"B", "KB", "MB", "GB", "TB"}

	var i int
	dblByte := float64(bytes)
	for i = 0; i < len(sizes) && bytes >= 1024; i++ {
		dblByte = float64(bytes) / 1024.0
		bytes /= 1024
	}

	return fmt.Sprintf("%.2f %s", dblByte, sizes[i])
}


/*
run:

8.93 TB
6.63 GB
22.65 MB
1.00 MB
1000.00 KB
852.97 KB
1.00 KB
978.00 B
13.00 B
0.00 B

*/

 



answered Aug 28, 2024 by avibootz
...