This commit is contained in:
aozhiwei 2023-08-12 15:09:40 +08:00
parent cadab4f094
commit 67c974caa2

View File

@ -7,34 +7,18 @@ import (
)
// ToInt converts a value to an integer.
func ToInt[T string | int | int64 | float32 | float64](value T) int {
var x interface{} = value
switch i := x.(type) {
case int:
return i
case int64:
return int(i)
case float32:
return int(i)
case float64:
return int(i)
case string:
intValue, err := strconv.Atoi(i)
if err != nil {
return 0
}
return intValue
}
return 0
func ToInt32[T string | int | int32 | int64 | float32 | float64](value T) int32 {
return int32(ToInt64(value))
}
// ToInt64 converts a value to an int64.
func ToInt64[T string | int | int64 | float32 | float64](value T) int64 {
func ToInt64[T string | int | int32 | int64 | float32 | float64](value T) int64 {
var x interface{} = value
switch i := x.(type) {
case int:
return int64(i)
case int32:
return int64(i)
case int64:
return i
case float32:
@ -51,12 +35,18 @@ func ToInt64[T string | int | int64 | float32 | float64](value T) int64 {
return 0
}
func ToFloat32[T string | int | int32 | int64 | float32 | float64](value T) float32 {
return float32(ToFloat64(value))
}
// ToFloat converts a value to a float64.
func ToFloat[T string | int | int64 | float32 | float64](value T) float64 {
func ToFloat64[T string | int | int32 | int64 | float32 | float64](value T) float64 {
var x interface{} = value
switch i := x.(type) {
case int:
return float64(i)
case int32:
return float64(i)
case int64:
return float64(i)
case float32:
@ -71,11 +61,13 @@ func ToFloat[T string | int | int64 | float32 | float64](value T) float64 {
}
// ToString converts a value to a string.
func ToString[T string | int | int64 | float32 | float64](value T) string {
func ToString[T string | int | int32 | int64 | float32 | float64](value T) string {
var x interface{} = value
switch i := x.(type) {
case int:
return strconv.Itoa(i)
case int32:
return strconv.Itoa(int(i))
case int64:
return strconv.FormatInt(i, 10)
case float32:
@ -92,6 +84,8 @@ func ToInt64Ex(x interface{}) (int64, error) {
switch i := x.(type) {
case int:
return int64(i), nil
case int32:
return int64(i), nil
case int64:
return i, nil
case float32:
@ -112,6 +106,8 @@ func ToFloat64Ex(x interface{}) (float64, error) {
switch i := x.(type) {
case int:
return float64(i), nil
case int32:
return float64(i), nil
case int64:
return float64(i), nil
case float32:
@ -129,6 +125,8 @@ func ToStringEx(x interface{}) (string, error) {
switch i := x.(type) {
case int:
return strconv.Itoa(i), nil
case int32:
return strconv.Itoa(int(i)), nil
case int64:
return strconv.FormatInt(i, 10), nil
case float32: