I. Overview
The official math
package provides a rounding method, round up math.Ceil()
, round downmath.Floor()
Two, usage
1 2 3 4 5 6 7 8 9 10 |
package main import ( "fmt" "math" ) func main(){ x := 1.1 fmt.Println(math.Ceil(x)) // 2 fmt.Println(math.Floor(x)) // 1 } |
It should be noted that what is returned after the completion is not a real integer, but a float64
type, so if you need a int
type, you need to convert it manually.
2017-10-14 Added: A wonderful rounding method
Golang does not have a python-like round() function. I searched a lot and it was very complicated. Finally I saw a fresh and refined one: first +0.5, then round down!
It is unbelievably simple, and there is nothing wrong with thinking about it. I admire this insight.
1 2 3 |
func round(x float64){ return int(math.Floor(x + 0/5)) } |