1 Star 0 Fork 0

h79/goutils

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
Clone or Download
integer.go 2.36 KB
Copy Edit Raw Blame History
huqiuyun authored 2024-02-19 13:58 . log
package common
import (
"reflect"
"strconv"
)
type IntegerType interface {
int8 | int16 | int | int32 | int64 | uint8 | uint16 | uint | uint32 | uint64 | float32 | float64
}
func SliceToInt(arr []interface{}) []int {
Int := make([]int, len(arr))
for i := range arr {
Int[i] = int(ToInt64(arr[i]))
}
return Int
}
func SliceToInt64(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()
case reflect.Float32:
fallthrough
case reflect.Float64:
return int64(reflectValue.Float())
default:
panic("unhandled default case")
}
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()
default:
panic("unhandled default case")
}
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()
default:
panic("unhandled default case")
}
return 0
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.101

Search