https://github.com/duke-git/lancet
https://blog.csdn.net/weixin_41155794/article/details/122299637
https://zhuanlan.zhihu.com/p/543391872
去重并去空字符串和null值
lit.TargetHost = slice.Compact(slice.Unique(targetHosts))
slice.Sort(lit.TargetHost)
// SliceUniqueCompact 去重并过滤空客串
func SliceUniqueCompact(paramSlice []string) []string {
if len(paramSlice) == 0 {
return []string{}
}
return slice.Compact(slice.Unique(paramSlice))
}
只添加不存在的值到切片中
var names = make([]string, 0, total)
names = slice.AppendIfAbsent(names, "lisi")
names = slice.AppendIfAbsent(names, "lisi")
fmt.Println(result3)
// Output:
// ["lisi"]
RoundToFloat 四舍五入,保留n位小数
fNumb = mathutil.RoundToFloat(avgTmp, 4) //保留4位小数
函数签名:
func RoundToFloat(x float64, n int) float64
示例:
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/mathutil"
)
func main() {
result1 := mathutil.RoundToFloat(0.124, 2)
result2 := mathutil.RoundToFloat(0.125, 2)
result3 := mathutil.RoundToFloat(0.125, 3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// 0.12
// 0.13
// 0.125
}
RoundToString
四舍五入,保留n位小数,返回字符串
函数签名:
func RoundToString(x float64, n int) string
TruncRound
截短n位小数(不进行四舍五入)
函数签名:
func TruncRound(x float64, n int) float64
百分比计算
a := 5
total := 10
proportion1 := fmt.Sprintf("%v%s", mathutil.Percent(float64(a), float64(total), 2), "%")
proportion := fmt.Sprintf("%.2f%s", mathutil.Percent(float64(a), float64(total), 2), "%")
fmt.Println("proportion1:", proportion1)
fmt.Println("proportion:", proportion)
// Output
// proportion1: 0.5%
// proportion: 0.50%
当月的开始时间
import "github.com/duke-git/lancet/v2/datetime"
input := time.Now().AddDate(-3, 0, 0) // 三年前
beginOfMonth := datetime.BeginOfMonth(input) //当月的开始时间
endOfMonth := datetime.EndOfMonth(input) //当月的结束时间
fmt.Println("beginOfMonth:", beginOfMonth)
fmt.Println("endOfMonth:", endOfMonth)
// Output
// beginOfMonth: 2020-09-01 00:00:00
// endOfMonth: 2020-09-30 23:59:59