-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |