hakk

software development, devops, and other drivel
Tree lined path

Golang Convert File Size to a human friendly format

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

1 KilloByte == 1024 Bytes

1 Megabyte == 1024*1024 Bytes

1 GigaByte == 102410241024 Bytes

package main

import (
	"fmt"
	"log"
	"math"
	"os"
	"strconv"
)

var (
	suffixes [5]string
)

func Round(val float64, roundOn float64, places int ) (newVal float64) {
	var round float64
	pow := math.Pow(10, float64(places))
	digit := pow * val
	_, div := math.Modf(digit)
	if div >= roundOn {
		round = math.Ceil(digit)
	} else {
		round = math.Floor(digit)
	}
	newVal = round / pow
	return
}

func HumanFileSize(size float64) string {
	fmt.Println(size)
	suffixes[0] = "B"
	suffixes[1] = "KB"
	suffixes[2] = "MB"
	suffixes[3] = "GB"
	suffixes[4] = "TB"
	
	base := math.Log(size)/math.Log(1024)
	getSize := Round(math.Pow(1024, base - math.Floor(base)), .5, 2)
	fmt.Println(int(math.Floor(base)))
	getSuffix := suffixes[int(math.Floor(base))]
	return strconv.FormatFloat(getSize, 'f', -1, 64)+" "+string(getSuffix)
}

func main() {
	files, err := os.ReadDir(".")
	if err != nil {
		log.Fatal(err)
	}

	for _, file := range files {
		fs := float64( file.Size() )
		fmt.Println(file.Name(), HumanFileSize(fs), file.ModTime())
	}
}