A brief description of the usage of golang round up, round down and rounding

I. Overview
The official math package provides a rounding method, rounding up math.Ceil() and rounding down math.Floor()

  1. Usage
    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 the returned integer is not a real integer, but a float64 type, so if you need an int type, you need to manually convert it.

2017-10-14 Append: a weird rounding method
Golang does not have a round() function similar to python. After searching a lot, it is very complicated. Finally, I saw a refreshing and refined one: +0.5 first, then round down!

It is unbelievably simple, and there is nothing wrong with thinking about it. This brain hole is very admirable.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish