From 20c83a9730c998c4622e2877556282b773904936 Mon Sep 17 00:00:00 2001 From: sumorf <529808348@qq.com> Date: Mon, 8 Oct 2018 14:04:58 +0800 Subject: [PATCH] add math2/math.go --- math2/math.go | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 math2/math.go diff --git a/math2/math.go b/math2/math.go new file mode 100644 index 0000000..59ff83a --- /dev/null +++ b/math2/math.go @@ -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 +}