Skip to content

Instantly share code, notes, and snippets.

@Urethramancer
Last active November 14, 2016 16:47
Show Gist options
  • Save Urethramancer/090011f19e48e054325a000875f15c0a to your computer and use it in GitHub Desktop.
Save Urethramancer/090011f19e48e054325a000875f15c0a to your computer and use it in GitHub Desktop.
Make human-readable number strings.
// humanNumber turns long numbers into sensible units for file sizes etc.
// Converted from C code found on the web.
func humanNumber(n int, si bool) string {
num := float64(n)
var unit float64 = 1024
if si {
unit = 1000
}
if num < unit {
return fmt.Sprintf("%dB", int(num))
}
exp := int(math.Log(num) / math.Log(unit))
pre := "kMGTPE"
if !si {
pre = "KMGTPE"
pre = pre[exp-1:exp] + "i"
} else {
pre = pre[exp-1 : exp]
}
r := n / int(math.Pow(unit, float64(exp)))
return fmt.Sprintf("%d %sB", r, pre)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment