fusenapi/utils/format/number.go

40 lines
758 B
Go
Raw Normal View History

2023-09-26 10:35:27 +00:00
package format
import (
2023-09-27 08:09:28 +00:00
"github.com/zeromicro/go-zero/core/logx"
2023-09-27 07:12:18 +00:00
"strconv"
2023-09-26 10:35:27 +00:00
"strings"
)
// 数字变成带千分位的字符串
2023-09-27 07:12:18 +00:00
func NumToStringWithThousandthPercentile(numberStr string) string {
if _, err := strconv.ParseFloat(numberStr, 64); err != nil {
2023-09-27 08:09:28 +00:00
logx.Error("is not a number")
2023-09-27 07:12:18 +00:00
return ""
}
2023-09-27 08:01:22 +00:00
sliceList := strings.Split(numberStr, ".") //切分开小数
2023-09-27 07:12:18 +00:00
s := sliceList[0]
f := ""
if len(sliceList) == 2 {
f = "." + sliceList[1]
}
2023-09-26 10:35:27 +00:00
l := len(s)
if l <= 3 {
2023-09-27 07:12:18 +00:00
return s + f
2023-09-26 10:35:27 +00:00
}
r := l % 3 //前面第几位开始加入千分位
2023-09-27 07:12:18 +00:00
if r == 0 {
r = 3
}
2023-09-26 10:35:27 +00:00
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
}
}
2023-09-27 07:12:18 +00:00
b.WriteString(f)
2023-09-26 10:35:27 +00:00
return b.String()
}