Go (golang) lets you round floating point numbers. To do so, you need to import the math module.
The official math package provides methods for rounding math.Ceil()
up and math.Floor()
down.
package main
import (
"fmt"
"math"
)
func main(){
x := 1.1
fmt.Println(math.Ceil(x)) // 2
fmt.Println(math.Floor(x)) // 1
}
Note that it is not a true integer that is returned after taking the whole, but a float64 type, so you need to convert it manually if you need an int type.
golang doesn't have a python-like round() function, and searched a lot of them to find a refreshing one: first +0.5, then round down!
It's incredibly simple, and there's nothing wrong with thinking about it:
func round(x float64){
return int(math.Floor(x + 0.5))
}
In a program that would look like:
package main
import (
"fmt"
"math"
)
func round(x float64) int{
return int(math.Floor(x + 0.5))
}
func main(){
fmt.Println(round(1.4))
fmt.Println(round(1.5))
fmt.Println(round(1.6))
}
Related links:
Top comments (1)
There is math.Round function that's equivalent to python's
round()
function:Try on Go Playground