-
Notifications
You must be signed in to change notification settings - Fork 0
/
floatx.go
52 lines (48 loc) · 1.45 KB
/
floatx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package floatx
import (
"math"
"strconv"
)
// FormatFloat
// 保留decimal位小数,舍弃尾数,无进位运算
// 先乘,trunc之后再除回去,就达到了保留N位小数的效果
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)
}
// FormatFloatCeil
// 保留decimal位小数, 舍弃的尾数不为0,强制进位
func FormatFloatCeil(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.Ceil(num*d)/d, 'f', -1, 64)
return strconv.ParseFloat(res, 64)
}
// FormatFloatFloor
// 保留decimal位小数, 强制舍弃尾数
func FormatFloatFloor(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.Floor(num*d)/d, 'f', -1, 64)
return strconv.ParseFloat(res, 64)
}