Skip to content

Commit

Permalink
Humanused numbers.
Browse files Browse the repository at this point in the history
  • Loading branch information
Urethramancer committed Mar 6, 2024
1 parent 4d03de3 commit feb812c
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions human/numbers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package human

import (
"fmt"
"math"
)

// UInt formats an unsigned 64-bit number into bytes, kilobytes etc. strings, optionally with SI numbers.
func UInt(n uint64, 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"
pre = pre[exp-1 : exp]
if !si {
pre = pre + "i"
}
r := n / uint64(math.Pow(unit, float64(exp)))
return fmt.Sprintf("%d %sB", r, pre)
}

0 comments on commit feb812c

Please sign in to comment.