diff --git a/exmath/benchmark/round_test.go b/exmath/benchmark/round_test.go new file mode 100644 index 0000000..bb09610 --- /dev/null +++ b/exmath/benchmark/round_test.go @@ -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) + } +} diff --git a/exmath/round.go b/exmath/round.go index a005cfe..712cf4e 100644 --- a/exmath/round.go +++ b/exmath/round.go @@ -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 } diff --git a/exmath/round_test.go b/exmath/round_test.go index c4f3bfa..3dc02c0 100644 --- a/exmath/round_test.go +++ b/exmath/round_test.go @@ -65,3 +65,4 @@ func TestRound(t *testing.T) { } } } +