package main
import (
"fmt"
"math"
"reflect"
"strconv"
)
func main() {
ToString(-1)
ToString(-123.456)
ToString(-987)
fmt.Println("ToString(math.Abs(-123))")
ToString(math.Abs(-123))
ToString(987)
ToString(3)
ToString(1.2345)
ToString(1234567890123456789)
ToString(1234e8)
}
// ToString Change arg to string
func ToString(arg interface{}) string {
var tmp = reflect.Indirect(reflect.ValueOf(arg)).Interface()
fmt.Printf("%T %v\n", tmp, tmp)
switch v := tmp.(type) {
case int:
return strconv.Itoa(v)
case int8:
return strconv.FormatInt(int64(v), 10)
case int16:
return strconv.FormatInt(int64(v), 10)
case int32:
return strconv.FormatInt(int64(v), 10)
case int64:
return strconv.FormatInt(v, 10)
case string:
return v
case float32:
return strconv.FormatFloat(float64(v), 'f', -1, 32)
case float64:
return strconv.FormatFloat(v, 'f', -1, 64)
default:
return ""
}
}
$ go run main.go
int -1
float64 -123.456
int -987
ToString(math.Abs(-123))
float64 123
int 987
int 3
float64 1.2345
int 1234567890123456789
float64 1.234e+11