DEV Community

Discussion on: I'm Go Backend developer and love it, Ask Me Anything!

Collapse
 
bregymr profile image
Bregy Malpartida

Following godoc of this function, Math.Round rounded any float to the nearest integer, rounding half away from zero (golang.org/pkg/math/#Round) and this function only exist from Go 1.10. If you want another more complex unit to round you can implement it.

func Round(x, unit float64) float64 {
    return math.Round(x/unit) * unit
}

fmt.Println(Round(12.3456, 0.01)) // 12.35 
fmt.Println(Round(0.363636, 0.01)) // 0.35
fmt.Println(Round(1.922636, 0.01)) // 1.92

You can round float and obteing a string without function Round, if you want you can convert your string to float later.

s := fmt.Sprintf("%.2f", 12.3456) // s == "12.35"

Here there good references
yourbasic.org/golang/round-float-2...
yourbasic.org/golang/round-float-t...