Skip to content
hakk
  • Home
  • Blog
  • Docs
  • DSA
  • Snippets

Size

  • Golang Convert File Size to a human friendly format 2020-06-09

    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())
    	}
    }
    

Recent posts
  • How to Update a File's Creation Time in PowerShell
  • How to Run PowerShell Code Only During Certain Times
  • PeopleSoft App Server Freeze Troubleshooting Checklist
  • Build Vim With Python3 Support
  • Understanding the ss Command: A Modern Alternative to netstat
© 2026 hakk
  • Home
  • Blog
  • Docs
  • DSA
  • Snippets