round a number to the nearest hundredth in go

To round a number to the nearest hundredth in Go, we can use the Round() function from the math package. Here's an example:

main.go
package main

import (
    "fmt"
    "math"
)

func main() {
    num := 12.3456789
    rounded := math.Round(num*100) / 100 // Multiply by 100, round, then divide by 100
    fmt.Printf("%.2f", rounded)
}
204 chars
13 lines

In this example, we first multiply the number by 100 to move the decimal point two places to the right, then use Round() to round the result to the nearest integer, and finally divide by 100 to move the decimal point back to its original position. The %f specifier in Printf() with the precision .2 is used to print the result to two decimal places. The output of this program will be:

main.go
12.35
6 chars
2 lines

which is the input number rounded to the nearest hundredth.

related categories

gistlibby LogSnag