round a number to the nearest tenth in go

One way to round a number to the nearest tenth in Go is to use the Round function from the math package. Here's an example:

main.go
package main
 
import (
    "fmt"
    "math"
)
 
func main() {
    num := 3.1415926
    rounded := math.Round(num*10) / 10
    fmt.Printf("%.1f", rounded)
}
157 chars
13 lines

In this example, we first define the number we want to round (num). Then we multiply it by 10 to move the digit we want to round to the ones place. We then use math.Round to round the number to the nearest integer value. Finally, we divide by 10 to move the digit back to the tenths place. We then use fmt.Printf to format the output with one decimal place.

This approach can also be generalized by creating a function that takes a number and a decimal place to round to:

main.go
func round(num float64, decimalPlaces int) float64 {
    factor := math.Pow10(decimalPlaces)
    return math.Round(num*factor) / factor
}
 
// Example usage:
rounded := round(3.1415926, 1)
189 chars
8 lines

gistlibby LogSnag