wp-go/helper/number/number.go

114 lines
2.0 KiB
Go
Raw Normal View History

2023-02-01 15:52:09 +00:00
// Package number
// 使用随机数时需要先 调用 rand.seed()函数
2023-01-21 11:31:23 +00:00
package number
import (
"fmt"
"golang.org/x/exp/constraints"
"math"
2023-01-21 11:31:23 +00:00
"math/rand"
2023-04-15 16:57:50 +00:00
"strconv"
2023-01-21 11:31:23 +00:00
)
func Range[T constraints.Integer](start, end, step T) []T {
2023-01-21 11:31:23 +00:00
if step == 0 {
panic("step can't be 0")
}
l := int((end-start+1)/step + 1)
if l < 0 {
l = 0 - l
}
r := make([]T, 0, l)
for i := start; ; {
r = append(r, i)
i = i + step
if (step > 0 && i > end) || (step < 0 && i < end) {
break
}
}
return r
}
2023-01-27 15:48:48 +00:00
// Rand 都为闭区间 [start,end]
func Rand[T constraints.Integer](start, end T) T {
2023-01-21 11:31:23 +00:00
end++
return T(rand.Int63n(int64(end-start))) + start
}
func Min[T constraints.Integer | constraints.Float](a ...T) T {
2023-01-21 11:31:23 +00:00
min := a[0]
for _, t := range a {
if min > t {
min = t
}
}
return min
}
func Max[T constraints.Integer | constraints.Float](a ...T) T {
2023-01-21 11:31:23 +00:00
max := a[0]
for _, t := range a {
if max < t {
max = t
}
}
return max
}
func Sum[T constraints.Integer | constraints.Float](a ...T) T {
2023-01-21 11:31:23 +00:00
s := T(0)
for _, t := range a {
s += t
}
return s
}
func Add[T constraints.Integer | constraints.Float](i, j T) T {
2023-01-27 15:48:48 +00:00
return i + j
}
func Sub[T constraints.Integer | constraints.Float](i, j T) T {
2023-01-28 13:38:34 +00:00
return i - j
}
2023-01-27 15:48:48 +00:00
func ToString[T constraints.Integer | constraints.Float](n T) string {
2023-01-21 11:31:23 +00:00
return fmt.Sprintf("%v", n)
}
2023-01-27 15:48:48 +00:00
2023-04-15 16:57:50 +00:00
func IntToString[T constraints.Integer](i T) string {
return strconv.FormatInt(int64(i), 10)
}
func Abs[T constraints.Integer | constraints.Float](n T) T {
2023-01-27 15:48:48 +00:00
if n >= 0 {
return n
}
return -n
}
2023-01-28 13:38:34 +00:00
func Mul[T constraints.Integer | constraints.Float](i, j T) T {
2023-01-28 13:38:34 +00:00
return i * j
}
func Divide[T constraints.Integer | constraints.Float](i, j T) T {
2023-01-28 13:38:34 +00:00
return i / j
}
func CalTotalPage[T constraints.Integer](totalRows, size T) T {
return T(math.Ceil(float64(totalRows) / float64(size)))
}
2023-03-19 12:40:08 +00:00
type Counter[T constraints.Integer] func() T
func Counters[T constraints.Integer]() func() T {
var count T
return func() T {
count++
return count
}
}
2023-07-04 15:36:25 +00:00
func Round(f float64, precision int) float64 {
p := math.Pow10(precision)
return math.Floor(f*p+0.5) / p
}