github.com/alibabacloud-go/tea@v1.3.10/dara/math.go (about)

     1  package dara
     2  
     3  import (
     4  	"math"
     5  	"math/rand"
     6  	"reflect"
     7  	"time"
     8  )
     9  
    10  // Number is an interface that can be implemented by any numeric type
    11  type Number interface{}
    12  
    13  // toFloat64 converts a numeric value to float64 for comparison
    14  func toFloat64(n Number) float64 {
    15  	v := reflect.ValueOf(n)
    16  	switch v.Kind() {
    17  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
    18  		return float64(v.Int())
    19  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
    20  		return float64(v.Uint())
    21  	case reflect.Float32, reflect.Float64:
    22  		return v.Float()
    23  	default:
    24  		panic("unsupported type")
    25  	}
    26  }
    27  
    28  // Floor returns the largest integer less than or equal to the input number as int
    29  func Floor(n Number) int {
    30  	v := toFloat64(n)
    31  	floorValue := math.Floor(v)
    32  	return int(floorValue)
    33  }
    34  
    35  // Round returns the nearest integer to the input number as int
    36  func Round(n Number) int {
    37  	v := toFloat64(n)
    38  	roundValue := math.Round(v)
    39  	return int(roundValue)
    40  }
    41  
    42  func Random() float64 {
    43  	rand.Seed(time.Now().UnixNano())
    44  	return rand.Float64()
    45  }