Skip to content

Instantly share code, notes, and snippets.

@jessestricker
Created August 24, 2016 16:16
Show Gist options
  • Save jessestricker/91424bcc03db4d75248e7093c721effa to your computer and use it in GitHub Desktop.
Save jessestricker/91424bcc03db4d75248e7093c721effa to your computer and use it in GitHub Desktop.
Byte Count Formatting
package util
import "fmt"
type ByteCount uint64
func (bc ByteCount) String() string {
const (
unitNames = "BKMGTPE" // E is sufficient for 64 bit values
maxValue = 1024
)
value, i := float64(bc), 0
for ; i < len(unitNames); i++ {
if value < maxValue {
break
}
value /= maxValue
}
unit := string(unitNames[i])
if i > 0 {
unit += "i" + string(unitNames[0])
}
return fmt.Sprintf("%.2f %v", value, unit)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment