Welcome To Golang By Example

Round a number in Go (Golang)

Table of Contents

Overview

math package of GO provides a Round method that can be used to round a number. It returns the nearest integer value.

Below is the signature of the function. It takes input a float and also returns a float.

func Round(x float64) float64

Some special cases of Round function are

Code:

package main

import (
    "fmt"
    "math"
)

func main() {
    res := math.Round(1.6)
    fmt.Println(res)

    res = math.Round(1.5)
    fmt.Println(res)

    res = math.Round(1.4)
    fmt.Println(res)

    res = math.Round(-1.6)
    fmt.Println(res)

    res = math.Round(-1.5)
    fmt.Println(res)

    res = math.Round(-1.4)
    fmt.Println(res)

    res = math.Round(1)
    fmt.Println(res)
}

Output:

2
2
1
-2
-2
-1
1