github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/f/float_round.go (about)

     1  package f
     2  
     3  import (
     4  	"fmt"
     5  	"math"
     6  	"strconv"
     7  	"strings"
     8  )
     9  
    10  // Round 四舍五入 小数点后 n 位
    11  func Round(v float64, n int) float64 {
    12  	shift := math.Pow(10, float64(n))
    13  	f := 0.0000000001 + v // 对浮点数产生.xxx999999999 计算不准进行处理
    14  	return math.Floor(f*shift+.5) / shift
    15  }
    16  
    17  // Floor 小数点后 n 位 - 舍去
    18  func Floor(v float64, n int) float64 {
    19  	floatStr := fmt.Sprintf("%."+strconv.Itoa(n+1)+"f", v)
    20  	temp := strings.Split(floatStr, ".")
    21  	var newFloat string
    22  	if len(temp) < 2 || n >= len(temp[1]) {
    23  		newFloat = floatStr
    24  	} else {
    25  		newFloat = temp[0] + "." + temp[1][:n]
    26  	}
    27  	f, _ := strconv.ParseFloat(newFloat, 64)
    28  	return f
    29  }