golang

Golang Round

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:

func Round(a float64) float64

It takes a float value and returns the nearest integer as float64.

Consider the examples below:

package main
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:

$ go run round.go
-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:

fmt.Println(reflect.TypeOf(math.Round(-1.6)))

The resulting output is as:

float64

To convert a float64 to int, you can cast as:

to_int := int64(math.Round(-1.6)

Go RoundToEven() Method

You can also use math.RoundToEven() function to convert a float value to its nearest even integer equivalent.

For example:

package main
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:

$ go run round.go

-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!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list