Format and Parse Human-Readable Byte Sizes
Format byte counts with binary units and parse human-readable sizes back into integers with rounding and unit validation.
Code
package main
import (
"fmt"
"math"
"strconv"
"strings"
)
var units = []string{"B", "KB", "MB", "GB", "TB", "PB"}
func formatBytes(value uint64) string {
if value < 1024 {
return fmt.Sprintf("%d B", value)
}
amount := float64(value)
unit := 0
for amount >= 1024 && unit < len(units)-1 {
amount /= 1024
unit++
}
precision := 0
if amount < 10 {
precision = 2
} else if amount < 100 {
precision = 1
}
return strconv.FormatFloat(amount, 'f', precision, 64) + " " + units[unit]
}
func parseBytes(text string) (uint64, error) {
fields := strings.Fields(strings.ToUpper(text))
if len(fields) != 2 {
return 0, fmt.Errorf("expected value and unit, got %q", text)
}
number, err := strconv.ParseFloat(fields[0], 64)
if err != nil || number < 0 {
return 0, fmt.Errorf("invalid size %q", fields[0])
}
index := -1
for candidate, unit := range units {
if unit == fields[1] {
index = candidate
break
}
}
if index < 0 {
return 0, fmt.Errorf("unknown unit %q", fields[1])
}
scale := math.Pow(1024, float64(index))
return uint64(math.Round(number * scale)), nil
}
func main() {
cases := []struct {
value uint64
want string
}{
{0, "0 B"},
{999, "999 B"},
{1024, "1.00 KB"},
{1536, "1.50 KB"},
{10 * 1024 * 1024, "10.0 MB"},
}
for _, tc := range cases {
got := formatBytes(tc.value)
fmt.Printf("%d -> %s\n", tc.value, got)
if got != tc.want {
panic("unexpected formatting: " + got)
}
}
parsed, err := parseBytes("1.5 MB")
if err != nil || parsed != 1572864 {
panic("unexpected parse result")
}
if _, err := parseBytes("12 XB"); err == nil {
panic("unknown unit should fail")
}
}
How the snippet works
Format and Parse Human-Readable Byte Sizes reduces to the functions formatBytes, parseBytes and main.
for amount >= 1024 && unit < len(units)-1 is the loop that carries the per-item work. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.
Watch out for
- Errors are ordinary return values; skipping the
errcheck means using a zero value silently.
Applying it
Entry signature: func formatBytes(value uint64) string
The sequence formatBytes and parseBytes lives in main; running the file triggers it.
Statements that decide the outcome
return 0, fmt.Errorf("expected value and unit, got %q", text)
return 0, fmt.Errorf("invalid size %q", fields[0])
return 0, fmt.Errorf("unknown unit %q", fields[1])
Interactive Tools for This Topic
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.
FAQ
- Does the snippet panic on failure?
- No exceptions — `error` returns checked at 2 sites, and callers branch on `err` first.
- How do you run Format and Parse Human-Readable Byte Sizes?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.