To round the float number to an integer in golang:
- Import the math package and use it in the golang program
- match package has a Round() function
- Round(x float64) function takes float type number as input
- It returns the nearest to an integer value, rounding half away from zero.
How to Round Float to Integer Value in Golang
Use the math.Round() function to round a floating-point number to an integer value in golang. Golang Round a float number to the nearest integer value.
Let’s understand rounding of float64 number to int value with an example.
package main import ( "fmt" "math" ) func main() { // Use math.Round to round floating-point number to nearest int fmt.Println(math.Round(3.3)) fmt.Println(math.Round(4.2)) fmt.Println(math.Round(2.8)) }
Output
3
4
3
In the above Golang program, we import the math
package to use the Round()
function.
The Round
function takes float64 as input and returns the nearest integer value.
How to Round Float Number to Even Number in Golang
Golang math package has a RoundToEven() function that returns the nearest integer number round to an even number.
Let’s understand the round of a float number to an even number in golang with an example.
package main import ( "fmt" "math" ) func main() { // Use math.Round to round floating-point number to nearest even intger fmt.Println(math.RoundToEven(-0.4)) fmt.Println(math.RoundToEven(-2.5)) fmt.Println(math.RoundToEven(5.7)) fmt.Println(math.RoundToEven(9.5)) }
Output
-0
-2
6
10
In the above golang program, the math
package RoundToEven
function takes the floating-point number as input and returns the nearest integer value, rounding ties to an even number.
Conclusion
I hope the above article helped you to understand how to round a float number to an int value in golang.
You can find more topics about the Golang tutorials on the GolangSpot Home page.
Recommended Content
Golang Float64 Max and Min Value
Golang Max and Min Value of Integer