1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
integer.go 2.12 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-01-15 02:41 . string
package common
import (
"reflect"
"strconv"
)
type IntegerType interface {
int8 | int16 | int | int32 | int64 | uint8 | uint16 | uint | uint32 | uint64 | float32 | float64
}
func AToInt(arr []interface{}) []int {
Int := make([]int, len(arr))
for i := range arr {
Int[i] = int(ToInt64(arr[i]))
}
return Int
}
func AToInt64(arr []interface{}) []int64 {
Int := make([]int64, len(arr))
for i := range arr {
Int[i] = ToInt64(arr[i])
}
return Int
}
func ToInt64(value interface{}) int64 {
reflectValue := reflect.Indirect(reflect.ValueOf(value))
return ToInt64V2(reflectValue)
}
func ToInt64V2(reflectValue reflect.Value) int64 {
switch reflectValue.Kind() {
case reflect.String:
if i, err := strconv.ParseInt(reflectValue.String(), 10, 64); err == nil {
return i
}
return 0
case reflect.Int:
fallthrough
case reflect.Int8:
fallthrough
case reflect.Int16:
fallthrough
case reflect.Int32:
fallthrough
case reflect.Int64:
return reflectValue.Int()
}
return 0
}
func ToFloat64(value interface{}) float64 {
reflectValue := reflect.Indirect(reflect.ValueOf(value))
return ToFloat64V2(reflectValue)
}
func ToFloat64V2(reflectValue reflect.Value) float64 {
switch reflectValue.Kind() {
case reflect.String:
f, _ := strconv.ParseFloat(reflectValue.String(), 4)
return f
case reflect.Int:
fallthrough
case reflect.Int8:
fallthrough
case reflect.Int16:
fallthrough
case reflect.Int32:
fallthrough
case reflect.Int64:
return float64(reflectValue.Int())
case reflect.Float32:
fallthrough
case reflect.Float64:
return reflectValue.Float()
}
return 0.0
}
func ToUInt64(value interface{}) uint64 {
reflectValue := reflect.Indirect(reflect.ValueOf(value))
return ToUInt64V2(reflectValue)
}
func ToUInt64V2(reflectValue reflect.Value) uint64 {
switch reflectValue.Kind() {
case reflect.String:
if i, err := strconv.ParseUint(reflectValue.String(), 10, 64); err == nil {
return i
}
return 0
case reflect.Uint:
fallthrough
case reflect.Uint8:
fallthrough
case reflect.Uint16:
fallthrough
case reflect.Uint32:
fallthrough
case reflect.Uint64:
return reflectValue.Uint()
}
return 0
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.4.14

搜索帮助