round a float in go

To round a float in Go, we can make use of the math package which provides various functions for mathematical operations. We can use the Round() function present in the math package to round a given float to the nearest integer.

Here's an example code snippet to demonstrate this:

main.go
package main

import (
    "fmt"
    "math"
)

func main() {
    num := 3.14159
    roundedNum := math.Round(num)
    fmt.Println(roundedNum) // Output: 3
}
157 chars
13 lines

In this example, we have imported the math package and used its Round() function to round the float value num to the nearest integer. The result is stored in roundedNum, which is then printed to the console.

If you want to round a float to a specific number of decimal places, you can use the Round() function in combination with Pow() function from the math package. Here's an example code snippet to demonstrate this:

main.go
package main

import (
    "fmt"
    "math"
)

func main() {
    num := 3.14159
    roundedNum := math.Round(num * 100) / 100
    fmt.Println(roundedNum) // Output: 3.14
}
172 chars
13 lines

In this example, we have multiplied the float value num by 100 to shift the decimal point two places to the right, then rounded off this value using Round(). Finally, we have divided the result by 100 to shift the decimal point back two places to the left, giving us the rounded value with two decimal places. The result is stored in roundedNum, which is then printed to the console.

related categories

gistlibby LogSnag