gconv_float.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gconv
  7. import (
  8. "strconv"
  9. "github.com/gogf/gf/v2/encoding/gbinary"
  10. )
  11. // Float32 converts `any` to float32.
  12. func Float32(any interface{}) float32 {
  13. if any == nil {
  14. return 0
  15. }
  16. switch value := any.(type) {
  17. case float32:
  18. return value
  19. case float64:
  20. return float32(value)
  21. case []byte:
  22. return gbinary.DecodeToFloat32(value)
  23. default:
  24. if f, ok := value.(iFloat32); ok {
  25. return f.Float32()
  26. }
  27. v, _ := strconv.ParseFloat(String(any), 64)
  28. return float32(v)
  29. }
  30. }
  31. // Float64 converts `any` to float64.
  32. func Float64(any interface{}) float64 {
  33. if any == nil {
  34. return 0
  35. }
  36. switch value := any.(type) {
  37. case float32:
  38. return float64(value)
  39. case float64:
  40. return value
  41. case []byte:
  42. return gbinary.DecodeToFloat64(value)
  43. default:
  44. if f, ok := value.(iFloat64); ok {
  45. return f.Float64()
  46. }
  47. v, _ := strconv.ParseFloat(String(any), 64)
  48. return v
  49. }
  50. }