Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save iambudi/a29be7123dfd50439c98f71a07e4e7dc to your computer and use it in GitHub Desktop.
Save iambudi/a29be7123dfd50439c98f71a07e4e7dc to your computer and use it in GitHub Desktop.
[Golang] Convert size in bytes to Bytes, Kilobytes, Megabytes, GB and TB
package main
import (
"fmt"
"math"
"strconv"
)
var (
sizeInMB float64 = 999 // This is in megabytes
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 main() {
size := sizeInMB * 1024 * 1024 // This is in bytes
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)
getSuffix := suffixes[int(math.Floor(base))]
fmt.Println(strconv.FormatFloat(getSize, 'f', -1, 64)+" "+string(getSuffix))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment