github.com/wangyougui/gf/v2@v2.6.5/util/gconv/gconv_float.go (about)

     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/wangyougui/gf.
     6  
     7  package gconv
     8  
     9  import (
    10  	"strconv"
    11  
    12  	"github.com/wangyougui/gf/v2/encoding/gbinary"
    13  )
    14  
    15  // Float32 converts `any` to float32.
    16  func Float32(any interface{}) float32 {
    17  	if any == nil {
    18  		return 0
    19  	}
    20  	switch value := any.(type) {
    21  	case float32:
    22  		return value
    23  	case float64:
    24  		return float32(value)
    25  	case []byte:
    26  		return gbinary.DecodeToFloat32(value)
    27  	default:
    28  		if f, ok := value.(iFloat32); ok {
    29  			return f.Float32()
    30  		}
    31  		v, _ := strconv.ParseFloat(String(any), 64)
    32  		return float32(v)
    33  	}
    34  }
    35  
    36  // Float64 converts `any` to float64.
    37  func Float64(any interface{}) float64 {
    38  	if any == nil {
    39  		return 0
    40  	}
    41  	switch value := any.(type) {
    42  	case float32:
    43  		return float64(value)
    44  	case float64:
    45  		return value
    46  	case []byte:
    47  		return gbinary.DecodeToFloat64(value)
    48  	default:
    49  		if f, ok := value.(iFloat64); ok {
    50  			return f.Float64()
    51  		}
    52  		v, _ := strconv.ParseFloat(String(any), 64)
    53  		return v
    54  	}
    55  }