You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

164 lines
2.3 KiB

package conver
import (
"math"
"strconv"
)
func ToInt64(inter any, defaultVal ...int64) int64 {
var def int64 = 0
if len(defaultVal) > 0 {
def = defaultVal[0]
}
switch v := inter.(type) {
default:
return def
case int:
return int64(v)
case int8:
return int64(v)
case int16:
return int64(v)
case int32:
return int64(v)
case int64:
return v
case uint8:
return int64(v)
case uint16:
return int64(v)
case uint32:
return int64(v)
case uint64:
return int64(v)
case float32:
return int64(v)
case float64:
if math.IsNaN(v) {
return def
}
return int64(v)
case bool:
if v {
return 1
}
return 0
case string:
a, e := strconv.Atoi(v)
if e != nil {
return def
}
return int64(a)
case *uint64:
if v == nil {
return def
}
return int64(*v)
case *int64:
if v == nil {
return def
}
return *v
}
}
func ToFloat64(inter any, defaultVal ...float64) (r float64) {
var def float64 = 0
if len(defaultVal) > 0 {
def = defaultVal[0]
}
defer func() {
if math.IsNaN(r) {
r = def
}
}()
switch v := inter.(type) {
default:
return def
case int:
return float64(v)
case int8:
return float64(v)
case int16:
return float64(v)
case int32:
return float64(v)
case int64:
return float64(v)
case uint8:
return float64(v)
case uint16:
return float64(v)
case uint32:
return float64(v)
case uint64:
return float64(v)
case float32:
return float64(v)
case float64:
return float64(v)
case *float64:
if v == nil {
return def
}
return *v
case *int64:
if v == nil {
return def
}
return float64(*v)
case string:
a, e := strconv.ParseFloat(v, 64)
if e != nil {
return def
}
return a
}
}
func ToBool(inter any, defaultVal ...bool) bool {
var def bool
if len(defaultVal) > 0 {
def = defaultVal[0]
}
switch v := inter.(type) {
default:
return def
case bool:
return v
case int:
return v > 0
case int8:
return v > 0
case int16:
return v > 0
case int32:
return v > 0
case int64:
return v > 0
case uint8:
return v > 0
case uint16:
return v > 0
case uint32:
return v > 0
case uint64:
return v > 0
case float32:
return v > 0
case float64:
return v > 0
case string:
a, e := strconv.ParseBool(v)
if e == nil {
return a
}
b, e := strconv.Atoi(v)
if e != nil {
return def
}
return b > 0
}
}