gitee.com/quant1x/num@v0.3.2/type_int64.go (about) 1 package num 2 3 import ( 4 "fmt" 5 "gitee.com/quant1x/gox/logger" 6 "gitee.com/quant1x/num/x32" 7 "gitee.com/quant1x/num/x64" 8 "math" 9 "strconv" 10 ) 11 12 const ( 13 MaxInt64 = int64(math.MaxInt64) 14 MinInt64 = int64(math.MinInt64) 15 Nil2Int64 = int64(0) // 空指针转int64 16 Int64NaN = int64(0) // int64 无效值 17 True2Int64 = int64(1) // true转int64 18 False2Int64 = int64(0) // false 转int64 19 StringBad2Int64 = int64(0) // 字符串解析int64异常 20 StringTrue2Int64 = int64(1) // 字符串true转int64 21 StringFalse2Int64 = int64(0) // 字符串false转int64 22 ) 23 24 // ParseInt64 解析int字符串, 尝试解析10进制和16进制 25 func ParseInt64(s string, v any) int64 { 26 defer func() { 27 // 解析失败以后输出日志, 以备检查 28 if err := recover(); err != nil { 29 logger.Errorf("ParseInt64 %+v, error=%+v\n", v, err) 30 } 31 }() 32 if IsEmpty(s) { 33 return Nil2Int64 34 } 35 if StringIsTrue(s) { 36 return StringTrue2Int64 37 } else if StringIsFalse(s) { 38 return StringFalse2Int64 39 } 40 if StringIsNaN(s) { 41 return StringFalse2Int64 42 } 43 i, err := strconv.ParseInt(s, 10, 64) 44 if err == nil { 45 return i 46 } 47 // 解析失败继续解析16进制 48 i, err = strconv.ParseInt(s, 16, 64) 49 if err == nil { 50 return i 51 } 52 logger.Errorf("%s, error=%+v\n", s, err) 53 if IgnoreParseExceptions { 54 i = StringBad2Int64 55 } else { 56 _ = v.(int64) // Intentionally panic 57 } 58 return i 59 } 60 61 func int64ToString(v int64) string { 62 if Float64IsNaN(float64(v)) { 63 return StringNaN 64 } 65 return fmt.Sprint(v) 66 } 67 68 // AnyToInt64 any转换int64 69 func AnyToInt64(v any) int64 { 70 if vv, ok := ExtractValueFromPointer(v); ok { 71 v = vv 72 } 73 74 f := valueToNumber[int64](v, Nil2Int64, BoolToInt64, ParseInt64) 75 return f 76 } 77 78 // SliceFloatToInt64 浮点转int64 79 func SliceFloatToInt64[T Float](x []T) []int64 { 80 switch values := any(x).(type) { 81 case []float32: 82 return x32.ToInt64(values) 83 case []float64: 84 return x64.ToInt64(values) 85 } 86 // 不可能走到这里 87 return []int64{} 88 }