Golang math.Round() Function with Examples

Golang | math.Round() Function: Here, we are going to learn about the Round() function of the math package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 03, 2021

math.Round()

The Round() function is an inbuilt function of the math package which is used to get the nearest integer, rounding half away from zero.

It accepts a parameter (x) and returns the nearest integer of the given value.

Syntax:

func Round(x float64) float64

Parameter(s):

  • x : The value whose nearest integer value is to be found.

Return Value:

The return type of Round() function is a float64, it returns the nearest integer, rounding half away from zero.

Special cases:

  • Round(±0) = ±0
    If the parameter is ±0, the function returns the same (±0).
  • Round(±Inf) = ±Inf
    If the parameter is ±Inf, the function returns the same (±Inf).
  • Round(NaN) = NaN
    If the parameter is NaN, the function returns the same (NaN).

Example 1:

// Golang program to demonstrate the
// example of math.Round() Function

package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println(math.Round(0.45))
	fmt.Println(math.Round(0.50))
	fmt.Println(math.Round(0.65))
	fmt.Println(math.Round(10.45))
	fmt.Println(math.Round(15.50))
	fmt.Println(math.Round(20.65))

	fmt.Println(math.Round(-0.45))
	fmt.Println(math.Round(-0.50))
	fmt.Println(math.Round(-0.65))
	fmt.Println(math.Round(-10.45))
	fmt.Println(math.Round(-15.50))
	fmt.Println(math.Round(-20.65))

	fmt.Println(math.Round(0))
	fmt.Println(math.Round(math.Inf(-1)))
	fmt.Println(math.Round(math.NaN()))
}

Output:

0
1
1
10
16
21
-0
-1
-1
-10
-16
-21
0
-Inf
NaN

Example 2:

// Golang program to demonstrate the
// example of math.Round() Function

package main

import (
	"fmt"
	"math"
)

func main() {
	var x float64
	var RoundX float64

	x = 16
	RoundX = math.Round(x)
	fmt.Println("Round(", x, ") = ", RoundX)

	x = 32.50
	RoundX = math.Round(x)
	fmt.Println("Round(", x, ") = ", RoundX)

	x = 64.60
	RoundX = math.Round(x)
	fmt.Println("Round(", x, ") = ", RoundX)

	x = -128.10
	RoundX = math.Round(x)
	fmt.Println("Round(", x, ") = ", RoundX)

	x = 0
	RoundX = math.Round(x)
	fmt.Println("Round(", x, ") = ", RoundX)

	x = -1
	RoundX = math.Round(x)
	fmt.Println("Round(", x, ") = ", RoundX)

	x = math.Inf(1)
	RoundX = math.Round(x)
	fmt.Println("Round(", x, ") = ", RoundX)

	x = math.NaN()
	RoundX = math.Round(x)
	fmt.Println("Round(", x, ") = ", RoundX)
}

Output:

Round( 16 ) =  16
Round( 32.5 ) =  33
Round( 64.6 ) =  65
Round( -128.1 ) =  -128
Round( 0 ) =  0
Round( -1 ) =  -1
Round( +Inf ) =  +Inf
Round( NaN ) =  NaN

Golang math Package Constants and Functions »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.