diff --git a/convert/bytes_common.go b/convert/bytes_common.go index 28ea9ac..0ade0c5 100644 --- a/convert/bytes_common.go +++ b/convert/bytes_common.go @@ -68,13 +68,20 @@ func ParseBytes(value string) (ByteAny, error) { // Meant as a universal function to be used by the implementations, with base and a list of unit names. // // A special behavior is that resulting values smaller than 2 are displayed with the lower exponent. +// If the input value is 0, humanReadable will always return "0B" // // Examples: // 1073741824B -> 1000KB // 2147483648B -> 2MB +// 0 -> 0MB // func humanReadable(b uint64, units []string, base float64) (float64, string) { + if b == 0 { + return 0, "B" + } + exponent := math.Log(float64(b)) / math.Log(base) + // Round to the unit scaled exponent unitExponent := math.Floor(exponent) diff --git a/convert/bytes_iec_test.go b/convert/bytes_iec_test.go index e83c3c3..2beb17b 100644 --- a/convert/bytes_iec_test.go +++ b/convert/bytes_iec_test.go @@ -6,6 +6,7 @@ import ( ) func TestBytesIEC_HumanReadable(t *testing.T) { + assert.Equal(t, "0B", BytesIEC(0).HumanReadable()) assert.Equal(t, "999B", BytesIEC(999).HumanReadable()) assert.Equal(t, "999KiB", BytesIEC(999*1024).HumanReadable()) assert.Equal(t, "999MiB", BytesIEC(999*1024*1024).HumanReadable()) diff --git a/convert/bytes_si_test.go b/convert/bytes_si_test.go index eb9c488..98d8b6e 100644 --- a/convert/bytes_si_test.go +++ b/convert/bytes_si_test.go @@ -6,6 +6,7 @@ import ( ) func TestBytesSI_HumanReadable(t *testing.T) { + assert.Equal(t, "0B", BytesSI(0).HumanReadable()) assert.Equal(t, "999B", BytesSI(999).HumanReadable()) assert.Equal(t, "999KB", BytesSI(999*1000).HumanReadable()) assert.Equal(t, "999MB", BytesSI(999*1000*1000).HumanReadable())