From adf18a2e47a9b9e0c74e06e20c043b8ae945315e Mon Sep 17 00:00:00 2001 From: dudaodong Date: Fri, 27 Sep 2024 10:18:37 +0800 Subject: [PATCH] fix: fix bug of Comma, issue #248 --- formatter/formatter.go | 11 ++++++++++- formatter/formatter_test.go | 4 ++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/formatter/formatter.go b/formatter/formatter.go index 163d8d4..ddb2bcd 100644 --- a/formatter/formatter.go +++ b/formatter/formatter.go @@ -26,16 +26,25 @@ func Comma[T constraints.Float | constraints.Integer | string](value T, symbol s return "" } + isNegative := strings.HasPrefix(numString, "-") + if isNegative { + numString = numString[1:] + } + index := strings.Index(numString, ".") if index == -1 { index = len(numString) } for index > 3 { - index = index - 3 + index -= 3 numString = numString[:index] + "," + numString[index:] } + if isNegative { + numString = "-" + numString + } + return symbol + numString } diff --git a/formatter/formatter_test.go b/formatter/formatter_test.go index fd3ce9a..7620934 100644 --- a/formatter/formatter_test.go +++ b/formatter/formatter_test.go @@ -28,6 +28,10 @@ func TestComma(t *testing.T) { assert.Equal("12,345.6789", Comma(+12345.6789, "")) assert.Equal("12,345,678.9", Comma(12345678.9, "")) assert.Equal("123,456,789,000", Comma(123456789000, "")) + + assert.Equal("-999", Comma(-999, "")) + assert.Equal("-1,000", Comma(-1000, "")) + assert.Equal("-1,234,567", Comma(-1234567, "")) } func TestPretty(t *testing.T) {