From 9c56f5f525b945c1b8bf860fd8818088f4acb545 Mon Sep 17 00:00:00 2001 From: Lee Sang Gyu Date: Mon, 9 Nov 2026 13:26:44 +0900 Subject: [PATCH] fix(package): [formatter] use the next byte unit when rounding hits base (#425) * fix(package): [formatter] use the next byte unit when rounding hits base * test(package): [formatter] cover byte unit rollover on rounding --- formatter/byte.go | 19 +++++++++++++++++-- formatter/byte_test.go | 7 +++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/formatter/byte.go b/formatter/byte.go index 2f02ccb..3a8553b 100644 --- a/formatter/byte.go +++ b/formatter/byte.go @@ -92,7 +92,7 @@ func DecimalBytes(size float64, precision ...int) string { pointPosition = precision[0] } - size, unit := calculateByteSize(size, 1000.0, decimalByteUnits) + size, unit := calculateRoundedByteSize(size, 1000.0, decimalByteUnits, pointPosition) return roundToToString(size, pointPosition) + unit } @@ -106,7 +106,7 @@ func BinaryBytes(size float64, precision ...int) string { pointPosition = precision[0] } - size, unit := calculateByteSize(size, 1024.0, binaryByteUnits) + size, unit := calculateRoundedByteSize(size, 1024.0, binaryByteUnits, pointPosition) return roundToToString(size, pointPosition) + unit } @@ -121,6 +121,21 @@ func calculateByteSize(size float64, base float64, byteUnits []string) (float64, return size, byteUnits[i] } +// calculateRoundedByteSize works like calculateByteSize, but moves to the next unit +// when the value rounds up to the base at the given (non-negative) precision (e.g. 999999 bytes +// with precision 2 gives 1MB instead of 1000KB). +func calculateRoundedByteSize(size float64, base float64, byteUnits []string, precision int) (float64, string) { + size, unit := calculateByteSize(size, base, byteUnits) + i := 0 + for byteUnits[i] != unit { + i++ + } + if precision >= 0 && i < len(byteUnits)-1 && mathutil.RoundToFloat(size, precision) >= base { + return size / base, byteUnits[i+1] + } + return size, unit +} + func roundToToString(x float64, max ...int) string { pointPosition := 4 if len(max) > 0 { diff --git a/formatter/byte_test.go b/formatter/byte_test.go index 897dec2..9fc29d3 100644 --- a/formatter/byte_test.go +++ b/formatter/byte_test.go @@ -28,6 +28,10 @@ func TestDecimalBytes(t *testing.T) { assert.Equal("4MB", DecimalBytes(4000000, 0)) assert.Equal("4MB", DecimalBytes(4000000, 1)) + + assert.Equal("1MB", DecimalBytes(999999, 2)) + assert.Equal("1GB", DecimalBytes(999999999, 2)) + assert.Equal("999.99KB", DecimalBytes(999990, 2)) } func TestBinaryBytes(t *testing.T) { @@ -43,6 +47,9 @@ func TestBinaryBytes(t *testing.T) { assert.Equal("10KiB", BinaryBytes(10240, 0)) assert.Equal("10KiB", BinaryBytes(10240, 1)) assert.Equal("10KiB", BinaryBytes(10240, 2)) + + assert.Equal("1MiB", BinaryBytes(1048575, 2)) + assert.Equal("1023.99KiB", BinaryBytes(1048566, 2)) } func TestParseDecimalBytes(t *testing.T) {