1
This commit is contained in:
parent
490774a7a3
commit
cadab4f094
102
convert.go
102
convert.go
@ -3,6 +3,7 @@ package q5
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// ToInt converts a value to an integer.
|
||||
@ -86,3 +87,104 @@ func ToString[T string | int | int64 | float32 | float64](value T) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func ToInt64Ex(x interface{}) (int64, error) {
|
||||
switch i := x.(type) {
|
||||
case int:
|
||||
return int64(i), nil
|
||||
case int64:
|
||||
return i, nil
|
||||
case float32:
|
||||
return int64(i), nil
|
||||
case float64:
|
||||
return int64(i), nil
|
||||
case string:
|
||||
intValue, err := strconv.ParseInt(i, 10, 64)
|
||||
if err != nil {
|
||||
return 0, nil
|
||||
}
|
||||
return intValue, nil
|
||||
}
|
||||
return 0, errors.New("ToInt64Ex error type")
|
||||
}
|
||||
|
||||
func ToFloat64Ex(x interface{}) (float64, error) {
|
||||
switch i := x.(type) {
|
||||
case int:
|
||||
return float64(i), nil
|
||||
case int64:
|
||||
return float64(i), nil
|
||||
case float32:
|
||||
return float64(i), nil
|
||||
case float64:
|
||||
return i, nil
|
||||
case string:
|
||||
f, _ := strconv.ParseFloat(strings.TrimSpace(i), 64)
|
||||
return f, nil
|
||||
}
|
||||
return 0, errors.New("ToFloat64Ex error type")
|
||||
}
|
||||
|
||||
func ToStringEx(x interface{}) (string, error) {
|
||||
switch i := x.(type) {
|
||||
case int:
|
||||
return strconv.Itoa(i), nil
|
||||
case int64:
|
||||
return strconv.FormatInt(i, 10), nil
|
||||
case float32:
|
||||
return strconv.FormatFloat(float64(i), 'f', -1, 32), nil
|
||||
case float64:
|
||||
return strconv.FormatFloat(i, 'f', -1, 64), nil
|
||||
case string:
|
||||
return i, nil
|
||||
}
|
||||
return "", errors.New("ToStringEx error type")
|
||||
}
|
||||
|
||||
func DuckToSimple[T string | int32 | int64 | float32 | float64](
|
||||
d interface{}, s *T) bool {
|
||||
var sx interface{} = s
|
||||
switch sv := sx.(type) {
|
||||
case *int32:
|
||||
{
|
||||
if val, err := ToInt64Ex(d); err == nil {
|
||||
*sv = int32(val)
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
case *int64:
|
||||
{
|
||||
if val, err := ToInt64Ex(d); err == nil {
|
||||
*sv = val
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
case *float32:
|
||||
{
|
||||
if val, err := ToFloat64Ex(d); err == nil {
|
||||
*sv = float32(val)
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
case *float64:
|
||||
{
|
||||
if val, err := ToFloat64Ex(d); err == nil {
|
||||
*sv = val
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
case *string:
|
||||
{
|
||||
if val, err := ToStringEx(d); err == nil {
|
||||
*sv = val
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user