1 Star 0 Fork 0

kzangv/gsf-lib

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
type_convert.go 2.16 KB
一键复制 编辑 原始数据 按行查看 历史
kzangv 提交于 2023-05-09 13:11 +08:00 . fixed
package glib
import (
"fmt"
"golang.org/x/exp/constraints"
"reflect"
"strconv"
)
func IntegerToString[R constraints.Integer](v R) string {
return fmt.Sprintf("%d", v)
}
func FloatToString[R constraints.Float](v R, prec int) string {
return fmt.Sprintf("%."+fmt.Sprintf("%d", prec)+"f", v)
}
func StringToInteger(v string) int {
ret, _ := strconv.Atoi(v)
return ret
}
func StringToFloat(v string) float64 {
val, _ := strconv.ParseFloat(v, 64)
return val
}
func ToString(val interface{}, limit ...int) string {
rv := reflect.ValueOf(val)
switch rv.Kind() {
case reflect.String:
return rv.String()
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return fmt.Sprintf("%d", val)
case reflect.Float32, reflect.Float64:
if len(limit) > 0 {
return fmt.Sprintf("%."+fmt.Sprintf("%d", limit[0])+"f", val)
}
return fmt.Sprintf("%f", val)
case reflect.Invalid:
return ""
default:
panic(fmt.Sprintf("[public.ToString][code:1] type:%T data:%v", val, val))
}
}
func ToInt(val interface{}) int {
rv := reflect.ValueOf(val)
switch rv.Kind() {
case reflect.String:
v, _ := strconv.Atoi(rv.String())
return v
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64:
return int(rv.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return int(rv.Uint())
case reflect.Float32, reflect.Float64:
return int(rv.Float())
case reflect.Invalid:
return 0
default:
panic(fmt.Sprintf("[public.ToInt][code:1] type:%T data:%v", val, val))
}
}
func ToFloat(val interface{}) float64 {
rv := reflect.ValueOf(val)
switch rv.Kind() {
case reflect.String:
v, _ := strconv.ParseFloat(rv.String(), 64)
return v
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64:
return float64(rv.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return float64(rv.Uint())
case reflect.Float32, reflect.Float64:
return rv.Float()
case reflect.Invalid:
return 0
default:
panic(fmt.Sprintf("[public.ToFloat][code:1] type:%T data:%v", val, val))
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/kzangv/gsf-lib.git
git@gitee.com:kzangv/gsf-lib.git
kzangv
gsf-lib
gsf-lib
v0.2.1

搜索帮助