fusenapi/utils/format/number.go
laodaming 9e2526405f fix
2023-09-27 15:12:18 +08:00

40 lines
706 B
Go

package format
import (
"log"
"strconv"
"strings"
)
// 数字变成带千分位的字符串
func NumToStringWithThousandthPercentile(numberStr string) string {
if _, err := strconv.ParseFloat(numberStr, 64); err != nil {
log.Fatalln("is not a number")
return ""
}
sliceList := strings.Split(numberStr, ".")
s := sliceList[0]
f := ""
if len(sliceList) == 2 {
f = "." + sliceList[1]
}
l := len(s)
if l <= 3 {
return s + f
}
r := l % 3 //前面第几位开始加入千分位
if r == 0 {
r = 3
}
b := strings.Builder{}
for i := 0; i < l; i++ {
b.WriteString(string(s[i]))
if i+1 == r && i != l-1 {
b.WriteString(",")
r += 3
}
}
b.WriteString(f)
return b.String()
}