1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-17 11:12:28 +08:00

fix: fix bug of Comma, issue #248

This commit is contained in:
dudaodong
2024-09-29 11:52:01 +08:00
parent 2145808268
commit 1d3585b22f
4 changed files with 19 additions and 6 deletions

View File

@@ -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.