5

golang向上取整、向下取整和四舍五入

 3 years ago
source link: https://studygolang.com/articles/12965?fr=sidebar
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

golang向上取整、向下取整和四舍五入

马谦的博客 · 2018-05-17 09:29:31 · 40710 次点击 · 预计阅读时间不到 1 分钟 · 不到1分钟之前 开始浏览    
这是一个创建于 2018-05-17 09:29:31 的文章,其中的信息可能已经有所发展或是发生改变。

官方的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 类型的话需要手动转换。

2017-10-14追加:一个奇葩的四舍五入方法

golang没有类似python的round()函数,搜了一下很多都非常复杂,最后看到了一个清新脱俗的:先+0.5,然后向下取整!

简单得难以置信,想想也没有什么不对,这脑洞很佩服。

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

有疑问加站长微信联系(非本文作者)

280

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:1006366459


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK