Skip to content

Commit

Permalink
Add ToFixedE5 method
Browse files Browse the repository at this point in the history
  • Loading branch information
f0cii committed Feb 29, 2020
1 parent 0e363d9 commit dc4b631
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
20 changes: 15 additions & 5 deletions math2/math.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,21 @@ package math2

import "math"

func Round(num float64) int {
return int(num + math.Copysign(0.5, num))
}

// ToFixed
func ToFixed(num float64, precision int) float64 {
output := math.Pow(10, float64(precision))
return float64(Round(num*output)) / output
return math.Round(num*output) / output
}

// ToFixedE5 类似四舍五入法,规整到 0,0.5,1.0,1.5...
// 用于 BitMEX/Deribit 等平台价格规整
func ToFixedE5(x float64) float64 {
t := math.Trunc(x)
if x > t+0.5 {
t += 0.5
}
if d := math.Abs(x - t); d > 0.25 {
return t + math.Copysign(0.5, x)
}
return t
}
12 changes: 12 additions & 0 deletions math2/math_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package math2

import (
"testing"
)

func TestR(t *testing.T) {
x := ToFixedE5(10000.51)
if x != 10000.5 {
t.Error("error")
}
}

0 comments on commit dc4b631

Please sign in to comment.