优化int64的转换

This commit is contained in:
Yun
2024-10-28 21:07:49 +08:00
parent 1be7f79ad3
commit 7a1b81ebf2
2 changed files with 31 additions and 20 deletions
+10 -3
View File
@@ -2,7 +2,7 @@ package convx
import (
"errors"
"strconv"
"math/big"
)
// interface 转 int64
@@ -37,7 +37,15 @@ func ToInt64(val interface{}) (i int64, err error) {
case float64:
return int64(v), nil
case string:
return strconv.ParseInt(v, 10, 64)
num := new(big.Float)
_, ok := num.SetString(v)
if !ok {
return 0, errors.New("convx.ToInt64: out of range")
}
i, _ := num.Int64()
// fmt.Println(val, i, b)
return i, nil
case bool:
if v {
return 1, nil
@@ -47,4 +55,3 @@ func ToInt64(val interface{}) (i int64, err error) {
}
return 0, errors.New("convx.ToInt64: unknown type")
}