Skip to content

Commit

Permalink
add math2/math.go
Browse files Browse the repository at this point in the history
  • Loading branch information
f0cii committed Oct 8, 2018
1 parent e755138 commit 20c83a9
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions math2/math.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package math2

import (
"math"
"strconv"
)

func ToFloat64(x string) float64 {
v, _ := strconv.ParseFloat(x, 64)
return v
}

// Round returns the nearest integer, rounding ties away from zero.
func Round(x float64) float64 {
t := math.Trunc(x)
if math.Abs(x-t) >= 0.5 {
return t + math.Copysign(1, x)
}
return t
}

// RoundToEven returns the nearest integer, rounding ties to an even number.
func RoundToEven(x float64) float64 {
t := math.Trunc(x)
odd := math.Remainder(t, 2) != 0
if d := math.Abs(x - t); d > 0.5 || (d == 0.5 && odd) {
return t + math.Copysign(1, x)
}
return t
}

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

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

0 comments on commit 20c83a9

Please sign in to comment.