In Go, you can round a floating-point number to a specific number of decimal places using the math.Round()
function from the math
package. Here's an example:
package main
import (
"fmt"
"math"
)
func main() {
num := 3.14159
rounded := Round(num, 2)
fmt.Println(rounded) // Output: 3.14
}
func Round(num float64, places int) float64 {
shift := math.Pow(10, float64(places))
return math.Round(num*shift) / shift
}
In this example, the Round()
function takes two arguments - the number to be rounded (num
) and the number of decimal places (places
). It multiplies the number by 10^places (shift
), rounds it to the nearest integer using math.Round()
, and then divides it by 10^places to get the rounded number.
You can adjust the num
and places
variables in the main()
function to round any floating-point number to a specific number of decimal places.