size
Before You Start
- Applies to: Go 1.21+ (examples verified with Go 1.22) · Prerequisites: Base: Data Types · Read time: about 8 min
dstgo/size is a convenient library for converting between strings and file sizes.
Repository: dstgo/size: Fast conversion between file size and string (github.com)
Documentation: dstgo/size: Fast conversion between file size and string (github.com)
Installation
$ go get https://github.com/dstgo/sizeUsage
const (
B Size = 1
KB = B * 1024
MB = KB * 1024
GB = MB * 1024
TB = GB * 1024
PB = TB * 1024
)type SizeMeta struct {
Data float64
Unit Size
}This library is very simple to use, with only two exposed functions:
func ParseSize(str string) SizeMetaParseSize converts a string into a SizeMeta struct, storing the data size and unit.
func ParseTargetSize(str string, size Size) SizeMetaParseTargetSize converts a string into a SizeMeta of the specified size.
Example:
package main
import (
"fmt"
"github.com/dstgo/size"
)
func main() {
parseSize := size.ParseSize("1.2MB")
fmt.Printf("%+v\n", parseSize)
fmt.Printf("%+v\n", parseSize.Round(1))
parseSize1 := size.ParseSize("2.3-asdajl")
fmt.Printf("%+v\n", parseSize1)
targetSize := size.ParseTargetSize("2.65MB", size.KB)
fmt.Printf("%+v", targetSize)
fmt.Printf("%+v", targetSize.String())
}After conversion, you can use the Round method to modify the number of decimal places to retain, or use the String method to get its string representation. Example output:
1.20MB
1.2
2713.60KBComplete Example
The program below runs as-is: copy it into a file and execute go run main.go, or paste it into the Go Playground.
package main
import "fmt"
func human(n int64) string {
units := []string{"B", "KB", "MB", "GB", "TB"}
f := float64(n)
i := 0
for f >= 1024 && i < len(units)-1 {
f /= 1024
i++
}
return fmt.Sprintf("%.1f%s", f, units[i])
}
func main() {
fmt.Println(human(1000), human(1024), human(1536), human(10485760))
}Expected output:
1000.0B 1.0KB 1.5KB 10.0MBCommon Pitfalls
- KB or KiB? Disk vendors use 1000, operating systems use 1024; state the convention in your UI.
- Rounding hides detail.
1.5KBcould be 1499 or 1536 bytes; keep the raw value for calculations. - Zero and negatives need a decision. Decide whether to show
0Bor0.0KB. - Presentation only. Never parse a humanised string back into a number; keep the integer.
- Locale formatting. Decimal separators differ; use the raw number in machine-readable output.
Change Log
- 2026-10-14: Added "Before You Start" notes, a complete runnable example with expected output, common pitfalls, and this change log. Closed a code block that was left unterminated.
