diff --git a/formatter/formatter.go b/formatter/formatter.go index f166919..b82da7d 100644 --- a/formatter/formatter.go +++ b/formatter/formatter.go @@ -32,9 +32,11 @@ func Comma[T constraints.Float | constraints.Integer | string](value T, prefixSy numString = numString[1:] } - index := strings.Index(numString, ".") - if index == -1 { - index = len(numString) + // Only the leading run of digits gets commas, so that an exponent ("1e+21") + // or any other suffix that ParseFloat accepts is left as it is. + index := 0 + for index < len(numString) && numString[index] >= '0' && numString[index] <= '9' { + index++ } for index > 3 { diff --git a/formatter/formatter_test.go b/formatter/formatter_test.go index 06ea417..453b752 100644 --- a/formatter/formatter_test.go +++ b/formatter/formatter_test.go @@ -35,6 +35,12 @@ func TestComma(t *testing.T) { assert.Equal("-999", Comma(-999, "")) assert.Equal("-1,000", Comma(-1000, "")) assert.Equal("-1,234,567", Comma(-1234567, "")) + + assert.Equal("1e+21", Comma("1e+21", "")) + assert.Equal("$12,345,678e3", Comma("12345678e3", "$")) + assert.Equal("1_000", Comma("1_000", "")) + assert.Equal("1,234,567.", Comma("1234567.", "")) + assert.Equal(".12345", Comma(".12345", "")) } func TestPretty(t *testing.T) {