round a number to the nearest integer in go

To round a floating-point number to the nearest integer in Go, you can use the Round function from the math package. This function rounds a floating-point number to the nearest integer, and returns it as a float64. To get an integer result, you can cast the rounded number to an integer using the int() function. Here's an example:

main.go
package main

import (
    "fmt"
    "math"
)

func main() {
    x := 2.7
    r := math.Round(x)
    i := int(r)
    fmt.Printf("x=%v, r=%v, i=%v\n", x, r, i)  // Output: x=2.7, r=3, i=3
}
189 chars
14 lines

In the example above, we declare a floating-point number x with the value of 2.7. We then use the Round function to round this value to the nearest integer, which is 3. We then cast the rounded value to an integer using the int() function, and store it in the variable i. We print out the original value, rounded value, and the integer value to verify that we've rounded x to the nearest integer.

gistlibby LogSnag