1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-09 07:02:29 +08:00

publish lancet

This commit is contained in:
dudaodong
2021-11-28 21:28:23 +08:00
parent 37edb0fc8f
commit 3254591ab9
38 changed files with 5163 additions and 0 deletions

17
formatter/formatter.go Normal file
View File

@@ -0,0 +1,17 @@
// Copyright 2021 dudaodong@gmail.com. All rights reserved.
// Use of this source code is governed by MIT license
// Package formatter implements some functions to format string, struct.
package formatter
import "strings"
// Comma add comma to number by every 3 numbers from right. ahead by symbol char
func Comma(v interface{}, symbol string) string {
s := numString(v)
dotIndex := strings.Index(s, ".")
if dotIndex != -1 {
return symbol + commaString(s[:dotIndex]) + s[dotIndex:]
}
return symbol + commaString(s)
}

View File

@@ -0,0 +1,25 @@
package formatter
import (
"github.com/duke-git/lancet/utils"
"testing"
)
func TestComma(t *testing.T) {
comma(t, "", "","")
comma(t, "aa", "","")
comma(t, "123", "","123")
comma(t, "12345", "","12,345")
comma(t, 12345, "","12,345")
comma(t, 12345, "$","$12,345")
comma(t, 12345, "¥","¥12,345")
comma(t, 12345.6789, "","12,345.6789")
}
func comma(t *testing.T, test interface{}, symbol string, expected interface{}) {
res:= Comma(test, symbol)
if res != expected {
utils.LogFailedTestInfo(t, "Comma", test, expected, res)
t.FailNow()
}
}

View File

@@ -0,0 +1,39 @@
package formatter
import (
"fmt"
"reflect"
"strconv"
"strings"
)
func commaString(s string) string {
if len(s) <= 3 {
return s
}
return commaString(s[:len(s)-3]) + "," + commaString(s[len(s)-3:])
}
func numString(value interface{}) string {
switch reflect.TypeOf(value).Kind() {
case reflect.Int, reflect.Int64, reflect.Float32, reflect.Float64:
return fmt.Sprintf("%v", value)
case reflect.String: {
sv := fmt.Sprintf("%v", value)
if strings.Contains(sv, ".") {
_, err := strconv.ParseFloat(sv, 64)
if err == nil {
return sv
}
}else {
_, err := strconv.ParseInt(sv, 10, 64)
if err == nil {
return sv
}
}
}
default:
return ""
}
return ""
}