DEV Community

Discussion on: Round numbers in Go

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