engine/utils/convert.go

107 lines
2.2 KiB
Go
Raw Permalink Normal View History

2024-02-11 01:31:01 +08:00
package utils
import (
"math"
"strconv"
"strings"
)
// 字符串转Int
2024-02-21 20:58:31 +08:00
//
// intStr数字的字符串
2024-02-11 01:31:01 +08:00
func String2Int(intStr string) (intNum int) {
intNum, _ = strconv.Atoi(intStr)
return
}
// 字符串转Int64
2024-02-21 20:58:31 +08:00
//
// intStr数字的字符串
2024-02-11 01:31:01 +08:00
func String2Int64(intStr string) (int64Num int64) {
intNum, _ := strconv.Atoi(intStr)
int64Num = int64(intNum)
return
}
// 字符串转Float64
2024-02-21 20:58:31 +08:00
//
// floatStr小数点数字的字符串
2024-02-11 01:31:01 +08:00
func String2Float64(floatStr string) (floatNum float64) {
floatNum, _ = strconv.ParseFloat(floatStr, 64)
return
}
// 字符串转Float32
2024-02-21 20:58:31 +08:00
//
// floatStr小数点数字的字符串
2024-02-11 01:31:01 +08:00
func String2Float32(floatStr string) (floatNum float32) {
floatNum64, _ := strconv.ParseFloat(floatStr, 32)
floatNum = float32(floatNum64)
return
}
// Int转字符串
2024-02-21 20:58:31 +08:00
//
// intNum数字字符串
2024-02-11 01:31:01 +08:00
func Int2String(intNum int) (intStr string) {
intStr = strconv.Itoa(intNum)
return
}
// Int64转字符串
2024-02-21 20:58:31 +08:00
//
// intNum数字字符串
2024-02-11 01:31:01 +08:00
func Int642String(intNum int64) (int64Str string) {
//10, 代表10进制
int64Str = strconv.FormatInt(intNum, 10)
return
}
// Float64转字符串
2024-02-21 20:58:31 +08:00
//
// floatNumfloat64数字
// prec精度位数不传则默认float数字精度
2024-02-11 01:31:01 +08:00
func Float64ToString(floatNum float64, prec ...int) (floatStr string) {
if len(prec) > 0 {
floatStr = strconv.FormatFloat(floatNum, 'f', prec[0], 64)
return
}
floatStr = strconv.FormatFloat(floatNum, 'f', -1, 64)
return
}
// Float32转字符串
2024-02-21 20:58:31 +08:00
//
// floatNumfloat32数字
// prec精度位数不传则默认float数字精度
2024-02-11 01:31:01 +08:00
func Float32ToString(floatNum float32, prec ...int) (floatStr string) {
if len(prec) > 0 {
floatStr = strconv.FormatFloat(float64(floatNum), 'f', prec[0], 32)
return
}
floatStr = strconv.FormatFloat(float64(floatNum), 'f', -1, 32)
return
}
// 二进制转10进制
func BinaryToDecimal(bit string) (num int) {
fields := strings.Split(bit, "")
lens := len(fields)
var tempF float64 = 0
for i := 0; i < lens; i++ {
floatNum := String2Float64(fields[i])
tempF += floatNum * math.Pow(2, float64(lens-i-1))
}
num = int(tempF)
return
}
// interface to string
func AnyToString(in any) (s string) {
if in == nil {
return ""
}
return in.(string)
}