round Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/round/ Wed, 25 Mar 2020 17:53:33 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 round Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/round/ 32 32 159787465 Round a number in Go (Golang) https://vikasboss.github.io/round-number-golang/ https://vikasboss.github.io/round-number-golang/#respond Wed, 25 Mar 2020 17:53:26 +0000 https://vikasboss.github.io/?p=1821 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...

The post Round a number in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
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

The post Round a number in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/round-number-golang/feed/ 0 1821