package format import ( "log" "strconv" "strings" ) // 数字变成带千分位的字符串 func NumToStringWithThousandthPercentile(numberStr string) string { numberStr = strings.TrimLeft(numberStr, "0") //去掉左边开始的0 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() }