github.com/wangyougui/gf/v2@v2.6.5/util/gconv/gconv_int.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package gconv 8 9 import ( 10 "math" 11 "strconv" 12 13 "github.com/wangyougui/gf/v2/encoding/gbinary" 14 ) 15 16 // Int converts `any` to int. 17 func Int(any interface{}) int { 18 if any == nil { 19 return 0 20 } 21 if v, ok := any.(int); ok { 22 return v 23 } 24 return int(Int64(any)) 25 } 26 27 // Int8 converts `any` to int8. 28 func Int8(any interface{}) int8 { 29 if any == nil { 30 return 0 31 } 32 if v, ok := any.(int8); ok { 33 return v 34 } 35 return int8(Int64(any)) 36 } 37 38 // Int16 converts `any` to int16. 39 func Int16(any interface{}) int16 { 40 if any == nil { 41 return 0 42 } 43 if v, ok := any.(int16); ok { 44 return v 45 } 46 return int16(Int64(any)) 47 } 48 49 // Int32 converts `any` to int32. 50 func Int32(any interface{}) int32 { 51 if any == nil { 52 return 0 53 } 54 if v, ok := any.(int32); ok { 55 return v 56 } 57 return int32(Int64(any)) 58 } 59 60 // Int64 converts `any` to int64. 61 func Int64(any interface{}) int64 { 62 if any == nil { 63 return 0 64 } 65 switch value := any.(type) { 66 case int: 67 return int64(value) 68 case int8: 69 return int64(value) 70 case int16: 71 return int64(value) 72 case int32: 73 return int64(value) 74 case int64: 75 return value 76 case uint: 77 return int64(value) 78 case uint8: 79 return int64(value) 80 case uint16: 81 return int64(value) 82 case uint32: 83 return int64(value) 84 case uint64: 85 return int64(value) 86 case float32: 87 return int64(value) 88 case float64: 89 return int64(value) 90 case bool: 91 if value { 92 return 1 93 } 94 return 0 95 case []byte: 96 return gbinary.DecodeToInt64(value) 97 default: 98 if f, ok := value.(iInt64); ok { 99 return f.Int64() 100 } 101 var ( 102 s = String(value) 103 isMinus = false 104 ) 105 if len(s) > 0 { 106 if s[0] == '-' { 107 isMinus = true 108 s = s[1:] 109 } else if s[0] == '+' { 110 s = s[1:] 111 } 112 } 113 // Hexadecimal 114 if len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') { 115 if v, e := strconv.ParseInt(s[2:], 16, 64); e == nil { 116 if isMinus { 117 return -v 118 } 119 return v 120 } 121 } 122 // Decimal 123 if v, e := strconv.ParseInt(s, 10, 64); e == nil { 124 if isMinus { 125 return -v 126 } 127 return v 128 } 129 // Float64 130 if valueInt64 := Float64(value); math.IsNaN(valueInt64) { 131 return 0 132 } else { 133 return int64(valueInt64) 134 } 135 } 136 }