You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
77 lines
1.8 KiB
77 lines
1.8 KiB
package xmath |
|
|
|
import ( |
|
"fmt" |
|
//"github.com/shopspring/decimal" |
|
"math" |
|
"math/rand" |
|
"strconv" |
|
"strings" |
|
) |
|
|
|
// 小数点后 n 位 - 四舍五入 |
|
func RoundedFixed(val float64, n int) float64 { |
|
shift := math.Pow(10, float64(n)) |
|
fv := 0.0000000001 + val //对浮点数产生.xxx999999999 计算不准进行处理 |
|
return math.Floor(fv*shift+.5) / shift |
|
} |
|
|
|
// 小数点后 n 位 - 舍去 |
|
func TruncRound(val float64, n int) float64 { |
|
floatStr := fmt.Sprintf("%."+strconv.Itoa(n+1)+"f", val) |
|
temp := strings.Split(floatStr, ".") |
|
var newFloat string |
|
if len(temp) < 2 || n >= len(temp[1]) { |
|
newFloat = floatStr |
|
} else { |
|
newFloat = temp[0] + "." + temp[1][:n] |
|
} |
|
inst, _ := strconv.ParseFloat(newFloat, 64) |
|
return inst |
|
} |
|
|
|
// RandInt64 随机范围取值 |
|
func RandInt64(min, max int64) int64 { |
|
if min >= max || min == 0 || max == 0 { |
|
return max |
|
} |
|
return rand.Int63n(max-min) + min |
|
} |
|
func FloatWithoutRightDot(n float64) string { |
|
s := fmt.Sprintf("%.2f", n) |
|
ss := strings.Split(s, ".") |
|
ss1 := strings.TrimRight(ss[1], "0") |
|
if ss1 == "" { |
|
return ss[0] |
|
} else { |
|
return fmt.Sprintf("%s.%s", ss[0], ss1) |
|
} |
|
} |
|
|
|
func NumberFormat(str string) string { |
|
length := len(str) |
|
if length < 4 { |
|
return str |
|
} |
|
arr := strings.Split(str, ".") //用小数点符号分割字符串,为数组接收 |
|
length1 := len(arr[0]) |
|
if length1 < 4 { |
|
return str |
|
} |
|
count := (length1 - 1) / 3 |
|
for i := 0; i < count; i++ { |
|
arr[0] = arr[0][:length1-(i+1)*3] + "," + arr[0][length1-(i+1)*3:] |
|
} |
|
return strings.Join(arr, ".") //将一系列字符串连接为一个字符串,之间用sep来分隔。 |
|
} |
|
|
|
func ConvertInt64(s string) int64 { |
|
v, _ := strconv.ParseInt(s, 10, 64) |
|
return v |
|
} |
|
|
|
// |
|
//func Round(f float64, n int32) float64 { |
|
// v, _ := decimal.NewFromFloat(f).Round(n).Float64() |
|
// return v |
|
//}
|
|
|