Go is a powerful programming language that comes with a collection of helpful packages and modules for various operations. One useful package is the math package. It contains methods and tools for performing mathematical operations with ease.
In this guide, you will learn how to round float values to the nearest integer using the built-in methods from the math package.
Go Round() Method
The math.Round() function allows you to round a float to the nearest integer, rounding halfway from zero.
The function is straightforward. The syntax is as shown:
It takes a float value and returns the nearest integer as float64.
Consider the examples below:
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Round(-1.6))
fmt.Println(math.Round(-1.4))
fmt.Println(math.Round(1.6))
fmt.Println(math.Round(1.4))
}
The above program returns the nearest integer values for the specified floats. An example output is as shown:
-2
-1
2
1
Keep in mind that the Round() function returns a float64. You can verify this using the Kind() method from the reflect package:
The resulting output is as:
To convert a float64 to int, you can cast as:
Go RoundToEven() Method
You can also use math.RoundToEven() function to convert a float value to its nearest even integer equivalent.
For example:
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.RoundToEven(-0.1))
fmt.Println(math.RoundToEven(-2.5))
fmt.Println(math.RoundToEven(3.7))
fmt.Println(math.RoundToEven(7.5))
}
The above code should return output as:
-0
-2
4
8
Similarly, the function returns a float64 type. Hence, you need to convert it to an integer if you require an int type.
Conclusion
This guide covered how to round a float into its nearest integer using the Round() and RoundToEven() methods.
Thanks for reading!