四捨五入 - skynocover/Wiki-for-GoLang GitHub Wiki
四捨五入
向上與向下取整
math.Ceil()
math.floor()
import (
"fmt"
"math"
)
func main(){
x := 1.1
fmt.Println(math.Ceil(x)) // 2
fmt.Println(math.Floor(x)) // 1
}
- 產生的數值為float而非int
四捨五入
func round(x float64){
return int(math.Floor(x + 0/5))
}
x:=1.49
fmt.Println(math.Round(x))
使用fmt
輸出時才決定四捨五入的位數
func main() {
var fs []float64 = []float64{1.15,1.16,1.25,1.26}
for _, f := range fs {
s := fmt.Sprintf("%.1f", f)
fmt.Println(f, "->", s)
}
}
1.15 -> 1.1
1.16 -> 1.2
1.25 -> 1.2
1.26 -> 1.3
五捨六入進位