Golang Round Float To Int Example

Go (Golang) provide a vast standard library which you can use for lots of different operations. When having to round a float to an integer value there is a simple way you could do that. By using the following method


Use math.Round

One option is math.Round. It’s extremely simple and intuitive here’s its definition

func Round(x float64) float64

Round returns the nearest integer, rounding half away from zero.

Here’s an example below for the math.Round


package main

import (
    "fmt"
    "math"
)

func main() { 
    fmt.Println(math.Round(2.3))
    fmt.Println(math.Round(2.7))
    fmt.Println(math.Round(2.0))
}

This is the expected output

2 3 2 

Use math.RoundToEven

Another option is math.RoundToEven when you need to convert the float number to its nearest even integer value

func RoundToEven(x float64) float64 

RoundToEven returns the nearest integer, rounding ties to even.

Here’s an example below for the math.RoundToEven


package main

import (
    "fmt"
    "math"
 )
 
 func main() {
     fmt.Println(math.RoundToEven(0.5))
     fmt.Println(math.RoundToEven(1.5))
     fmt.Println(math.RoundToEven(3.5))
}

This is the expected output

0 2 4 

Got Questions? Join our Slack community