github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/misc/amount-convert/rmb.go (about)

     1  package amount
     2  
     3  import (
     4  	"fmt"
     5  	"math"
     6  	"strconv"
     7  )
     8  
     9  // FenToYuan from fen to yuan
    10  func FenToYuan(a int64) float64 {
    11  	return Int64ToFloat64(a, 2)
    12  }
    13  
    14  // YuanToFen from yun to fen
    15  func YuanToFen(a float64) int64 {
    16  	return Float64ToInt64(a, 2)
    17  }
    18  
    19  // convert int64 to float64
    20  func Int64ToFloat64(n int64, decimal int) float64 {
    21  	var negative bool
    22  	if n < 0 {
    23  		negative = true
    24  		n = -n
    25  	}
    26  	k := int64(math.Pow10(decimal))
    27  	head := n / k
    28  	tail := n % k
    29  	format := "%d.%0" + fmt.Sprintf("%d", decimal) + "d"
    30  	str := fmt.Sprintf(format, head, tail)
    31  	f, err := strconv.ParseFloat(str, 64)
    32  	if err != nil {
    33  		panic(fmt.Sprintf("convert int64[%d] to float64[decimal:%d] failed[err:%s]", n, decimal, err.Error()))
    34  	}
    35  	if negative {
    36  		f = -f
    37  	}
    38  	return f
    39  }
    40  
    41  // convert floa64 to int64
    42  func Float64ToInt64(f float64, decimal int) int64 {
    43  	var negative bool
    44  	if f < 0 {
    45  		negative = true
    46  		f = -f
    47  	}
    48  	k := math.Pow10(decimal)
    49  	str := fmt.Sprintf("%.0f", f*k)
    50  	n, err := strconv.ParseInt(str, 10, 64)
    51  	if err != nil {
    52  		panic(fmt.Sprintf("convert float64[%f] to float64[decimal:%d] failed[err:%s]", f, decimal, err.Error()))
    53  	}
    54  	if negative {
    55  		n = -n
    56  	}
    57  	return n
    58  }
    59  
    60  // Round 四舍五入
    61  func Round(v float64, decimals int) float64 {
    62  	var pow float64 = 1
    63  	for i := 0; i < decimals; i++ {
    64  		pow *= 10
    65  	}
    66  	return float64(int((v*pow)+0.5)) / pow
    67  }
    68  
    69  /*
    70  利息罚息计算(通过年化利率计算)
    71  本金-capital
    72  年化利率-rate
    73  计息天数-dateDiff
    74  保留位数-decimals
    75  单位-分
    76  */
    77  func CountInterestByAnnualizedRate(capital, rate float64, dateDiff, decimals int) float64 {
    78  	return Round(float64(capital*float64(dateDiff)*rate/360), decimals)
    79  }