gitee.com/quant1x/num@v0.3.2/decimals.go (about)

     1  package num
     2  
     3  import (
     4  	"math"
     5  )
     6  
     7  func IsNaN(f float64) bool {
     8  	return math.IsNaN(f) || math.IsInf(f, 0)
     9  }
    10  
    11  // Decimal 保留小数点四舍五入
    12  func Decimal(value float64, digits ...int) float64 {
    13  	defaultDigits := 2
    14  	if len(digits) > 0 {
    15  		defaultDigits = digits[0]
    16  		if defaultDigits < 0 {
    17  			defaultDigits = 0
    18  		}
    19  	}
    20  	if IsNaN(value) {
    21  		value = float64(0)
    22  	}
    23  	half := 0.5
    24  	if math.Signbit(value) {
    25  		// 如果是负值, 半数用-0.5
    26  		half = -0.5
    27  	}
    28  	n10 := math.Pow10(defaultDigits)
    29  	return math.Trunc((value+half/n10)*n10) / n10
    30  }
    31  
    32  // NetChangeRate 净增长率, 去掉百分比
    33  func NetChangeRate[B Number, C Number](baseValue B, currentValue C) (changeRate float64) {
    34  	changeRate = ChangeRate(baseValue, currentValue)
    35  	changeRate = (changeRate - 1.00) * 100.00
    36  	return changeRate
    37  }
    38  
    39  // ChangeRate 增长率
    40  func ChangeRate[B Number, C Number](baseValue B, currentValue C) (changeRate float64) {
    41  	return float64(currentValue) / float64(baseValue)
    42  }