官方的math 包中提供了取整的方法,向上取整math.Ceil() ,向下取整math.Floor()

package main
import (
    "fmt"
    "math"
)
func main(){
    x := 1.1
    fmt.Println(math.Ceil(x))  // 2
    fmt.Println(math.Floor(x))  // 1
}

要注意的是,取完整后返回的并不是真正的整数,而是float64 类型,所以如果需要int 类型的话需要手动转换。

go四舍五入,先加0.5然后向下取整。

func round(x float64)int{
    return int(math.Floor(x + 0/5))
}

或使用math.round(f float64)

var f float64=1.333
var b int=int(math.round(f))