Round Value of a Number
To find round value of a number in Go language, use Round() function of math package. Round(x) returns the nearest integer to x
, rounding half away from zero.
In this tutorial, we will learn the syntax of Round() function, and how to use this function to find the round value of a given number.
Syntax
The syntax of Round() function is
math.Round(x)
where x
is a floating point value of type float64.
Please note that we have to import “math” package to use Round() function.
Return Value
The function returns a floating point value of type float64.
Examples
Round Value of 3.14
In the following program, we take a float value of 3.14 in x
, and find its round value.
example.go
package main import ( "fmt" "math" ) func main() { x := 3.14 result := math.Round(x) fmt.Println("Round Value :", result) }
Output
Round Value : 3
For x = 3.14, 3 is the nearest integer rounding half way from 0.
Round Value of 3.85
In the following program, we find the round value of 3.85. Since, 4 is the nearest integer to 3.85, Round(3.85) must return 4.
example.go
package main import ( "fmt" "math" ) func main() { x := 3.85 result := math.Round(x) fmt.Println("Round Value :", result) }
Output
Round Value : 4
Round Value of 3.5
Let us take the mid value between 3 and 4, which is 3.5. In the following example, we find the round value of 3.5.
example.go
package main import ( "fmt" "math" ) func main() { x := 3.5 result := math.Round(x) fmt.Println("Round Value :", result) }
Output
Round Value : 4
Conclusion
In this Golang Tutorial, we learned how to find round value of a given float value in Go language, with example programs.