mirror of
https://github.com/kataras/iris.git
synced 2026-01-09 13:05:56 +00:00
add mathx.RoundToInteger helper
This commit is contained in:
@@ -26,3 +26,18 @@ func RoundDown(input float64, places float64) float64 {
|
||||
pow := math.Pow(10, places)
|
||||
return math.Floor(pow*input) / pow
|
||||
}
|
||||
|
||||
// RoundToInteger rounds the given float64 to an integer.
|
||||
func RoundToInteger(x float64) int {
|
||||
// If the number is 1.1 round it to the previous integer (1), if >= 1.11 round it to the next one (2).
|
||||
t := math.Trunc(x)
|
||||
odd := math.Remainder(t, 2) != 0
|
||||
d := math.Abs(x - t)
|
||||
d = Round(d, 0.5, 2) // round to 2 decimals so we can easily check 0.11 and 0.1 and 0.2.
|
||||
if d > 0.1 || (d == 0.2 && odd) {
|
||||
// fmt.Printf("%f-%f -> %f. Is > 0.1 -> %v \n", x, t, d, d > 0.1)
|
||||
t = t + math.Copysign(1, x)
|
||||
return int(t)
|
||||
}
|
||||
return int(t)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user