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 (
func main() {

The above program returns the nearest integer values for the specified floats. An example output is as shown:

$ go run round.go

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:

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 (
func main() {

The above code should return output as:

$ go run round.go


Similarly, the function returns a float64 type. Hence, you need to convert it to an integer if you require an int type.


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