Golang math.Round() Function

Golang math.Round() function is “used to find the nearest integer, rounding half away from zero”. It takes a floating-point number as an argument and returns the rounded integer value of that number. The returned value is of type float64.

Syntax

func Round(x float64) float64

Parameters

x: The Round() function accepts a floating-point number as an argument.

Return value

  1. If you pass -Inf or +Inf in the Round() function like Round(-Inf) or Round(+Inf), it will return -Inf or +Inf.
  2. If you pass -0 or +0 in the Round() function, like Round(-0) or Round(+0), it will return -0 or +0.
  3. Passing NaN in the Round() function like Round(NaN) will return NaN.

Example 1

package main

import (
  "fmt"
  "math"
)

func main() {
  data := 19.21
  result := math.Round(data)
  fmt.Println("The Rounded Value :", result)
}

Output

The Rounded Value : 19

Example 2

Let’s execute an example where the floating value is 19.29.

package main

import (
  "fmt"
  "math"
)

func main() {
  data := 19.29
  result := math.Round(data)
  fmt.Println("The Rounded Value :", result)
}

Output

The Rounded Value : 19

Example 3

Here’s an example of how to pass a negative floating-point number in math.Round() function in Go.

package main

import (
  "fmt"
  "math"
)

func main() {
  data := -19.29
  result := math.Round(data)
  fmt.Println("The Rounded Value :", result)
}

Output

The Rounded Value : -19

That’s it.

Related posts

Golang math.Ceil()

Golang math.Min()

Golang math.Floor()

Golang math.Pow()

Golang math.Mod()

Leave a Comment