RoundToInteger rounds the given float64 to an integer.
(x float64)
| 29 | |
| 30 | // RoundToInteger rounds the given float64 to an integer. |
| 31 | func RoundToInteger(x float64) int { |
| 32 | // If the number is 1.1 round it to the previous integer (1), if >= 1.11 round it to the next one (2). |
| 33 | t := math.Trunc(x) |
| 34 | odd := math.Remainder(t, 2) != 0 |
| 35 | d := math.Abs(x - t) |
| 36 | d = Round(d, 0.5, 2) // round to 2 decimals so we can easily check 0.11 and 0.1 and 0.2. |
| 37 | if d > 0.1 || (d == 0.2 && odd) { |
| 38 | // fmt.Printf("%f-%f -> %f. Is > 0.1 -> %v \n", x, t, d, d > 0.1) |
| 39 | t = t + math.Copysign(1, x) |
| 40 | return int(t) |
| 41 | } |
| 42 | return int(t) |
| 43 | } |