Skip to content

Commit

Permalink
Merge pull request #13 from thinkeridea/exmath.Round
Browse files Browse the repository at this point in the history
调优exmath.Round算法
  • Loading branch information
thinkeridea authored Jan 2, 2021
2 parents dd12918 + d9408dd commit 23f0fa7
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
14 changes: 14 additions & 0 deletions exmath/benchmark/round_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package benchmark

import (
"testing"

"github.com/thinkeridea/go-extend/exmath"
)

func BenchmarkRound(b *testing.B) {
f := 0.15807659924030304
for i := 0; i < b.N; i++ {
_ = exmath.Round(f, 5)
}
}
2 changes: 1 addition & 1 deletion exmath/round.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ import (
// 返回将 val 根据指定精度 precision(十进制小数点后数字的数目)进行四舍五入的结果。precision 也可以是负数或零。
func Round(val float64, precision int) float64 {
p := math.Pow10(precision)
return math.Floor((val+(0.5/p))*p) / p
return math.Floor(val*p+0.5) / p
}
1 change: 1 addition & 0 deletions exmath/round_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,4 @@ func TestRound(t *testing.T) {
}
}
}

0 comments on commit 23f0fa7

Please sign in to comment.