bitbucket.org/ai69/amoy@v0.2.3/math.go (about)

     1  package amoy
     2  
     3  import (
     4  	"math"
     5  )
     6  
     7  // FractionCeil returns the least integer value greater than or equal to a/b.
     8  func FractionCeil(a, b int) int {
     9  	return int(math.Ceil(float64(a) / float64(b)))
    10  }
    11  
    12  // FractionFloor returns the greatest integer value less than or equal to a/b.
    13  func FractionFloor(a, b int) int {
    14  	return int(math.Floor(float64(a) / float64(b)))
    15  }
    16  
    17  // FractionFractional returns the fractional part of floating-point number represented by a/b.
    18  func FractionFractional(a, b int) float64 {
    19  	_, f := math.Modf(float64(a) / float64(b))
    20  	return f
    21  }
    22  
    23  // FractionTrunc returns the integer value of a/b.
    24  func FractionTrunc(a, b int) int {
    25  	return int(math.Trunc(float64(a) / float64(b)))
    26  }
    27  
    28  // FractionRound returns the nearest integer, rounding half away from zero of a/b.
    29  func FractionRound(a, b int) int {
    30  	return int(math.Round(float64(a) / float64(b)))
    31  }
    32  
    33  // Fractional returns the fractional part of floating-point number f.
    34  func Fractional(f float64) float64 {
    35  	_, f = math.Modf(f)
    36  	return f
    37  }
    38  
    39  // CountDigit returns the number of digits of a number.
    40  func CountDigit(num int) int {
    41  	if num == 0 {
    42  		return 1
    43  	}
    44  	return int(math.Floor(math.Log10(math.Abs(float64(num))) + 1))
    45  }
    46  
    47  // PercentageStr returns the percentage of a/b as a string.
    48  func PercentageStr(a, b int) string {
    49  	var s string
    50  	if b == 0 || a == 0 {
    51  		s = "0"
    52  	} else if a == b {
    53  		s = "100"
    54  	} else {
    55  		s = FtoaWithDigits(float64(a)/float64(b)*100, 2)
    56  	}
    57  	return s + "%"
    58  }
    59  
    60  // RoundToFixed returns the rounding floating number with given precision.
    61  func RoundToFixed(num float64, precision int) float64 {
    62  	if precision < 0 || precision > 12 {
    63  		return num
    64  	}
    65  	mul := math.Pow(10, float64(precision))
    66  	return math.Round(num*mul) / mul
    67  }