From d5752499bf61b5a46f2d619b8d092a6628ebbd77 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Mon, 29 Jul 2024 11:42:56 +0800 Subject: [PATCH] fix: remove scientific notation in DecimalBytes --- formatter/byte.go | 19 ++++++++++++++++--- formatter/byte_test.go | 6 ++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/formatter/byte.go b/formatter/byte.go index eb1b0c3..7355035 100644 --- a/formatter/byte.go +++ b/formatter/byte.go @@ -84,13 +84,26 @@ var ( // The precision parameter specifies the number of digits after the decimal point, which defaults to 4. // Play: https://go.dev/play/p/FPXs1suwRcs func DecimalBytes(size float64, precision ...int) string { - p := 5 + pointPosition := 4 if len(precision) > 0 { - p = precision[0] + 1 + pointPosition = precision[0] } + size, unit := calculateByteSize(size, 1000.0, decimalByteUnits) - return fmt.Sprintf("%.*g%s", p, size, unit) + format := fmt.Sprintf("%%.%df", pointPosition) + result := fmt.Sprintf(format, size) + + for i := len(result); i > 0; i-- { + s := result[i-1] + if s == '0' || s == '.' { + result = result[:i-1] + } else { + break + } + } + + return result + unit } // BinaryBytes returns a human-readable byte size under binary standard (base 1024) diff --git a/formatter/byte_test.go b/formatter/byte_test.go index fb9a618..07d8482 100644 --- a/formatter/byte_test.go +++ b/formatter/byte_test.go @@ -20,6 +20,12 @@ func TestDecimalBytes(t *testing.T) { assert.Equal("3.123PB", DecimalBytes(float64(3.123*UnitPB))) assert.Equal("4.123EB", DecimalBytes(float64(4.123*UnitEB))) assert.Equal("1EB", DecimalBytes(float64(1000*UnitPB))) + + assert.Equal("62MB", DecimalBytes(61812496, 0)) + assert.Equal("61.8MB", DecimalBytes(61812496, 1)) + assert.Equal("401MB", DecimalBytes(401000000)) + assert.Equal("401MB", DecimalBytes(401000000, 0)) + assert.Equal("4MB", DecimalBytes(4010000, 0)) } func TestBinaryBytes(t *testing.T) {