优化数字格式化

This commit is contained in:
GoEdgeLab
2022-10-15 19:33:07 +08:00
parent 221730a70e
commit 6619b3b162
2 changed files with 32 additions and 0 deletions

View File

@@ -82,6 +82,30 @@ func FormatFloat(f interface{}, decimal int) string {
switch x := f.(type) {
case float32, float64:
var s = fmt.Sprintf("%."+types.String(decimal)+"f", x)
// 分隔
var dotIndex = strings.Index(s, ".")
if dotIndex > 0 {
var d = s[:dotIndex]
var l = len(d)
if l > 3 {
var f2 = s[dotIndex:] // 包含点(.
var pieces = l / 3
var commIndex = l - pieces*3
var d2 = ""
if commIndex > 0 {
d2 = d[:commIndex] + ", "
}
for i := 0; i < pieces; i++ {
d2 += d[commIndex + i*3 : commIndex + i*3+3]
if i != pieces-1 {
d2 += ", "
}
}
return d2 + f2
}
}
return s
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return types.String(x)

View File

@@ -33,6 +33,14 @@ func TestFormatFloat(t *testing.T) {
t.Log(numberutils.FormatFloat(100.23456, 2))
t.Log(numberutils.FormatFloat(100.000023, 2))
t.Log(numberutils.FormatFloat(100.012, 2))
t.Log(numberutils.FormatFloat(123.012, 2))
t.Log(numberutils.FormatFloat(1234.012, 2))
t.Log(numberutils.FormatFloat(12345.012, 2))
t.Log(numberutils.FormatFloat(123456.012, 2))
t.Log(numberutils.FormatFloat(1234567.012, 2))
t.Log(numberutils.FormatFloat(12345678.012, 2))
t.Log(numberutils.FormatFloat(123456789.012, 2))
t.Log(numberutils.FormatFloat(1234567890.012, 2))
}
func TestTrimZeroSuffix(t *testing.T) {