DEV Community

natamacm
natamacm

Posted on

Round numbers in Go

#go

Go (golang) lets you round floating point numbers. To do so, you need to import the math module.

The official math package provides methods for rounding math.Ceil() up and math.Floor() down.

package main

import (
 "fmt"
 "math"
)

func main(){
 x := 1.1
 fmt.Println(math.Ceil(x))  // 2
 fmt.Println(math.Floor(x))  // 1
}

Note that it is not a true integer that is returned after taking the whole, but a float64 type, so you need to convert it manually if you need an int type.

golang doesn't have a python-like round() function, and searched a lot of them to find a refreshing one: first +0.5, then round down!

It's incredibly simple, and there's nothing wrong with thinking about it:

func round(x float64){
    return int(math.Floor(x + 0.5))
}

In a program that would look like:

package main

import (
 "fmt"
 "math"
)

func round(x float64) int{
    return int(math.Floor(x + 0.5))
}

func main(){
 fmt.Println(round(1.4))
 fmt.Println(round(1.5))
 fmt.Println(round(1.6))
}

Related links:

Top comments (1)

Collapse
 
krlv profile image
eugene kirillov • Edited

golang doesn't have a python-like round() function

There is math.Round function that's equivalent to python's round() function:

package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Printf("%v\n", math.Round(1.4))
    // Output: 1
    fmt.Printf("%v\n", math.Round(-1.4))
    // Output: -1

    fmt.Printf("%v\n", math.Round(1.5))
    // Output: 2
    fmt.Printf("%v\n", math.Round(-1.5))
    // Output: -1

    fmt.Printf("%v\n", math.Round(1.6))
    // Output: 2
    fmt.Printf("%v\n", math.Round(-1.6))
    // Output: -2
}

Try on Go Playground