ok
This commit is contained in:
76
conv/conv.go
Normal file
76
conv/conv.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package conv
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// AnyToString 任意类型转字符串
|
||||
// in: 输入值
|
||||
// 返回: 转换后的字符串
|
||||
func AnyToString(in any) (s string) {
|
||||
if in == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return in.(string)
|
||||
}
|
||||
|
||||
// AnyToInt 将动态类型转为 int(两仓库 internal 中逻辑一致,此处合并分支)。
|
||||
func AnyToInt(v any) int {
|
||||
switch val := v.(type) {
|
||||
case int:
|
||||
return val
|
||||
case int8:
|
||||
return int(val)
|
||||
case int16:
|
||||
return int(val)
|
||||
case int32:
|
||||
return int(val)
|
||||
case int64:
|
||||
return int(val)
|
||||
case uint, uint8, uint16, uint32, uint64:
|
||||
return int(reflect.ValueOf(val).Uint())
|
||||
case float32:
|
||||
return int(val)
|
||||
case float64:
|
||||
return int(val)
|
||||
case string:
|
||||
i, err := strconv.Atoi(val)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return i
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// AnyToFloat64 将动态类型转为 float64(合并 stock 对 int/uint 等分支与 gostock 的 string 分支)。
|
||||
func AnyToFloat64(v any) float64 {
|
||||
switch val := v.(type) {
|
||||
case float64:
|
||||
return val
|
||||
case string:
|
||||
return String2Float64(val)
|
||||
case float32:
|
||||
return float64(val)
|
||||
case int:
|
||||
return float64(val)
|
||||
case uint:
|
||||
return float64(val)
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// String2Float64 字符串转Float64
|
||||
// floatStr: 小数点数字的字符串
|
||||
// 返回: 转换后的64位浮点数,转换失败返回0
|
||||
func String2Float64(floatStr string) (floatNum float64) {
|
||||
floatNum, err := strconv.ParseFloat(floatStr, 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return
|
||||
}
|
||||
Reference in New Issue
Block a user