What is the RoundToEven function in Golang?

The RoundToEven function is used to round the given argument to the nearest integer where the rounding ties to even.

"Ties to even" is a rounding strategy where floating-point numbers that are exactly in the middle of two integer numbers, like 1.5 is between 1 and 2, are rounded towards the even number, be it smaller or greater than the original integer.

To use this function, you must import the math package in your file and access the RoundToEven function within it using the . notation (math.RoundToEven). Here, RoundToEven is the actual function, while math is the Go package that stores the definition of this function.

Function definition

The definition of the RoundToEven function inside the math package is as follows:

Parameters

The RoundToEven function takes a single argument of type float64. This argument represents the number to be rounded off.

Return value

The RoundToEven function returns a single value of type float64 that represents the rounder value of the passed integer.

Some special cases:

  • If the argument has an (+-)Inf value, the return value has the same sign as the argument.

  • If the value of the passed argument is NAN, the return value will be NAN.

Code

Below is a simple example where we round off an integer, tied to even.

package main
import(
"fmt"
"math"
)
func main() {
var x float64 = 8.5
z := math.RoundToEven(x)
fmt.Print("The Rounding to even for ", x, " is: ", z)
}

The example below shows how the RoundToEven function handles NAN values in its arguments.

Here, we use the NaN function present in the math package to generate a NAN value.

package main
import(
"fmt"
"math"
)
func main() {
x := math.NaN()
z := math.RoundToEven(x)
fmt.Print("The Rounding to even for ", x, " is: ", z)
}