53 lines
945 B
Go
53 lines
945 B
Go
package convx
|
|
|
|
import (
|
|
"strconv"
|
|
|
|
"errors"
|
|
)
|
|
|
|
// interface 转 float64
|
|
func ToFloat64(val interface{}) (f float64, err error) {
|
|
|
|
switch v := val.(type) {
|
|
case nil:
|
|
return 0, errors.New("val is nil")
|
|
case float32:
|
|
return float64(v), nil
|
|
case float64:
|
|
return v, nil
|
|
case int:
|
|
return float64(v), nil
|
|
case int8:
|
|
return float64(v), nil
|
|
case int16:
|
|
return float64(v), nil
|
|
case int32:
|
|
return float64(v), nil
|
|
case int64:
|
|
return float64(v), nil
|
|
case uint:
|
|
return float64(v), nil
|
|
case uint8:
|
|
return float64(v), nil
|
|
case uint16:
|
|
return float64(v), nil
|
|
case uint32:
|
|
return float64(v), nil
|
|
case uint64:
|
|
return float64(v), nil
|
|
case string:
|
|
return strconv.ParseFloat(v, 64)
|
|
case bool:
|
|
if v {
|
|
return 1, nil
|
|
} else {
|
|
return 0, nil
|
|
}
|
|
case []byte:
|
|
return strconv.ParseFloat(string(v), 64)
|
|
}
|
|
|
|
return 0, errors.New("convx.ToFloat64: unknown type")
|
|
}
|