113 lines
2.3 KiB
Go
113 lines
2.3 KiB
Go
package utils
|
|
|
|
import (
|
|
"github.com/shopspring/decimal"
|
|
"math/rand"
|
|
"strconv"
|
|
)
|
|
|
|
// RandInt 生成 [min, max] 范围内的随机整数
|
|
func RandInt(min, max int) int {
|
|
if min > max {
|
|
min, max = max, min
|
|
}
|
|
return rand.Intn(max-min+1) + min
|
|
}
|
|
|
|
// StringToInt64 converts a string to int64, returns 0 if failed
|
|
func StringToInt64(s string) int64 {
|
|
i, err := strconv.ParseInt(s, 10, 64)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
return i
|
|
}
|
|
|
|
// Int64ToString converts int64 to string
|
|
func Int64ToString(i int64) string {
|
|
return strconv.FormatInt(i, 10)
|
|
}
|
|
|
|
// AddFloat64 对浮点数求和
|
|
func AddFloat64(places int32, number ...float64) float64 {
|
|
if len(number) == 0 {
|
|
return 0
|
|
}
|
|
result := decimal.NewFromFloat(0)
|
|
for _, n := range number {
|
|
result = result.Add(decimal.NewFromFloat(n))
|
|
}
|
|
return result.Round(places).InexactFloat64()
|
|
}
|
|
|
|
// SubFloat64 对浮点数求差
|
|
func SubFloat64(places int32, number ...float64) float64 {
|
|
if len(number) == 0 {
|
|
return 0
|
|
}
|
|
result := decimal.NewFromFloat(number[0])
|
|
for i := 1; i < len(number); i++ {
|
|
result = result.Sub(decimal.NewFromFloat(number[i]))
|
|
}
|
|
return result.Round(places).InexactFloat64()
|
|
}
|
|
|
|
// MulFloat64 对浮点数求积
|
|
func MulFloat64(places int32, number ...float64) float64 {
|
|
if len(number) == 0 {
|
|
return 0
|
|
}
|
|
result := decimal.NewFromFloat(1)
|
|
for _, n := range number {
|
|
result = result.Mul(decimal.NewFromFloat(n))
|
|
}
|
|
return result.Round(places).InexactFloat64()
|
|
}
|
|
|
|
// DivFloat64 对浮点数求商
|
|
func DivFloat64(places int32, number ...float64) float64 {
|
|
if len(number) == 0 {
|
|
return 0
|
|
}
|
|
result := decimal.NewFromFloat(number[0])
|
|
for i := 1; i < len(number); i++ {
|
|
if number[i] == 0 {
|
|
return 0 // 避免除以零
|
|
}
|
|
result = result.Div(decimal.NewFromFloat(number[i]))
|
|
}
|
|
return result.Round(places).InexactFloat64()
|
|
}
|
|
|
|
// MaxInt32 返回两个 int32 中的较大值
|
|
func MaxInt32(a, b int32) int32 {
|
|
if a > b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|
|
|
|
// MinInt32 返回两个 int32 中的较小值
|
|
func MinInt32(a, b int32) int32 {
|
|
if a < b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|
|
|
|
// MaxFloat64 返回两个 float64 中的较大值
|
|
func MaxFloat64(a, b float64) float64 {
|
|
if a > b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|
|
|
|
// MinFloat64 返回两个 float64 中的较小值
|
|
func MinFloat64(a, b float64) float64 {
|
|
if a < b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|