Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Round a number in Go (Golang)

Posted on March 25, 2020March 25, 2020 by admin

Table of Contents

  • Overview
  • Code:

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

  • Round(±0) = ±0
  • Round(±Inf) = ±Inf
  • Round(NaN) = NaN

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
  • golang
  • math
  • round
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme