Last active
November 14, 2016 16:47
-
-
Save Urethramancer/090011f19e48e054325a000875f15c0a to your computer and use it in GitHub Desktop.
Make human-readable number strings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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