human
Human-readable size formatting for Go.
Features
- Binary Units: Uses 1024 as base (KB, MB, GB, etc.)
- Decimal Units: Uses 1000 as base (KB, MB, GB, etc.)
- Auto-scaling: Automatically selects appropriate unit
- Precision Control: Shows decimals only when needed
Usage
import "gitea.loveuer.com/loveuer/upkg/tool/human"
Binary Format (1024 base)
human.Size(1024) // "1 KB"
human.Size(1024 * 1024) // "1 MB"
human.Size(1536) // "1.50 KB"
human.Size(-1024 * 1024) // "-1 MB"
Decimal Format (1000 base)
human.SizeDecimal(1000) // "1 KB"
human.SizeDecimal(1000000) // "1 MB"
human.SizeDecimal(1000000000) // "1 GB"
Binary (SI-compatible)
human.SizeBinary(1000) // "976.56 KB"
human.SizeBinary(1000000) // "953.67 MB"
Performance
| Function | ns/op | B/op | allocs |
|---|---|---|---|
| Size | 439 | 32 | 3 |
| SizeDecimal | 387 | 32 | 3 |
| SizeBinary | 558 | 40 | 3 |
Examples
package main
import (
"fmt"
"gitea.loveuer.com/loveuer/upkg/tool/human"
)
func main() {
fmt.Println(human.Size(1024)) // 1 KB
fmt.Println(human.Size(1024 * 1024)) // 1 MB
fmt.Println(human.Size(1024 * 1024 * 1024)) // 1 GB
fmt.Println(human.Size(1500)) // 1.46 KB
fmt.Println(human.Size(0)) // 0 B
}