diff --git a/math2/math.go b/math2/math.go index 7a0e0cb..86f975e 100644 --- a/math2/math.go +++ b/math2/math.go @@ -29,6 +29,29 @@ func RoundToEven(x float64) float64 { return t } +// Round4BitMEX 类似四舍五入法 +// XBT: precision=0 0,0.5,1.0,1.5... +// ETH: precision=1 0.05,0.10,0.15... +func Round4BitMEX(x float64, precision int) float64 { + if precision == 0 { + return round4BitMEX(x) + } + p := math.Pow(10, float64(precision)) + y := float64(round4BitMEX(x*p)) / p + return y +} + +func round4BitMEX(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 +} + // RoundToEven5 类似四舍五入法,规整到 0,0.5,1.0,1.5... func RoundToEven5(x float64) float64 { t := math.Trunc(x)