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.

28 lines
580 B

package utils
import (
"fmt"
"math"
"strconv"
)
func FormatFloat(num float64, decimal int) (float64, error) {
// 默认乘1
d := float64(1)
if decimal > 0 {
// 10的N次方
d = math.Pow10(decimal)
}
// math.trunc作用就是返回浮点数的整数部分
// 再除回去,小数点后无效的0也就不存在了
res := strconv.FormatFloat(math.Trunc(num*d)/d, 'f', -1, 64)
return strconv.ParseFloat(res, 64)
}
func FormatFloatToString(num float64) string {
float, err := FormatFloat(num, 2)
if err != nil {
return "-"
}
return fmt.Sprintf("%v", float)
}