diff --git a/docs/formatter.md b/docs/formatter.md index f7d2f54..61993dc 100644 --- a/docs/formatter.md +++ b/docs/formatter.md @@ -42,7 +42,7 @@ Param should be number or numberic string.
Signature: ```go -func Comma(value interface{}, symbol string) string +func Comma(value interface{}, prefixSymbol string) string ``` Example: diff --git a/docs/formatter_zh-CN.md b/docs/formatter_zh-CN.md index 4e97367..ad77a9a 100644 --- a/docs/formatter_zh-CN.md +++ b/docs/formatter_zh-CN.md @@ -41,7 +41,7 @@ import ( 函数签名: ```go -func Comma(v interface{}, symbol string) string +func Comma(v interface{}, prefixSymbol string) string ``` 例子: diff --git a/formatter/formatter.go b/formatter/formatter.go index e7fb426..a2ae4db 100644 --- a/formatter/formatter.go +++ b/formatter/formatter.go @@ -16,10 +16,10 @@ import ( "github.com/duke-git/lancet/convertor" ) -// Comma add comma to a number value by every 3 numbers from right. ahead by symbol char. +// Comma add comma to a number value by every 3 numbers from right. ahead by prefix symbol char. // if value is invalid number string eg "aa", return empty string // Comma("12345", "$") => "$12,345", Comma(12345, "$") => "$12,345" -func Comma(value interface{}, symbol string) string { +func Comma(value interface{}, prefixSymbol string) string { numString := convertor.ToString(value) _, err := strconv.ParseFloat(numString, 64) @@ -27,17 +27,26 @@ func Comma(value interface{}, symbol string) string { 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:] } - return symbol + numString + if isNegative { + numString = "-" + numString + } + + return prefixSymbol + numString } // Pretty data to JSON string. diff --git a/formatter/formatter_test.go b/formatter/formatter_test.go index 5023da7..75fd560 100644 --- a/formatter/formatter_test.go +++ b/formatter/formatter_test.go @@ -26,6 +26,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) {