mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
fix: fix bug of Comma, issue #248
This commit is contained in:
@@ -42,7 +42,7 @@ Param should be number or numberic string.</p>
|
||||
<b>Signature:</b>
|
||||
|
||||
```go
|
||||
func Comma(value interface{}, symbol string) string
|
||||
func Comma(value interface{}, prefixSymbol string) string
|
||||
```
|
||||
|
||||
<b>Example:</b>
|
||||
|
||||
@@ -41,7 +41,7 @@ import (
|
||||
<b>函数签名:</b>
|
||||
|
||||
```go
|
||||
func Comma(v interface{}, symbol string) string
|
||||
func Comma(v interface{}, prefixSymbol string) string
|
||||
```
|
||||
|
||||
<b>例子:</b>
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user