Created
August 24, 2016 16:16
-
-
Save jessestricker/91424bcc03db4d75248e7093c721effa to your computer and use it in GitHub Desktop.
Byte Count Formatting
This file contains 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
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