Skip to content

Commit 23f0fa7

Browse files
authored
Merge pull request #13 from thinkeridea/exmath.Round
调优exmath.Round算法
2 parents dd12918 + d9408dd commit 23f0fa7

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

exmath/benchmark/round_test.go

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package benchmark
2+
3+
import (
4+
"testing"
5+
6+
"github.com/thinkeridea/go-extend/exmath"
7+
)
8+
9+
func BenchmarkRound(b *testing.B) {
10+
f := 0.15807659924030304
11+
for i := 0; i < b.N; i++ {
12+
_ = exmath.Round(f, 5)
13+
}
14+
}

exmath/round.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,5 @@ import (
1111
// 返回将 val 根据指定精度 precision(十进制小数点后数字的数目)进行四舍五入的结果。precision 也可以是负数或零。
1212
func Round(val float64, precision int) float64 {
1313
p := math.Pow10(precision)
14-
return math.Floor((val+(0.5/p))*p) / p
14+
return math.Floor(val*p+0.5) / p
1515
}

exmath/round_test.go

+1
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,4 @@ func TestRound(t *testing.T) {
6565
}
6666
}
6767
}
68+

0 commit comments

Comments
 (0)