To format and print numbers with a specific number of decimal places in Go, you can use the fmt.Printf()
or fmt.Sprintf()
functions along with the formatting verbs. Here's an example:
package main
import "fmt"
func main() {
num := 3.14159
// Format and print with 2 decimal places
fmt.Printf("%.2f\n", num)
// Format and store as a string with 3 decimal places
formattedNum := fmt.Sprintf("%.3f", num)
fmt.Println(formattedNum)
}
Output:
3.14
3.142
In the example above, %.2f
specifies that the number should be formatted with 2 decimal places, and %f
is the formatting verb for floating-point numbers. You can change the number after the dot to adjust the number of decimal places.
You can also use fmt.Sprintf()
to format the number as a string with a specific number of decimal places. In the example, %.3f
specifies that the number should be formatted with 3 decimal places. The formatted number is then stored in the formattedNum
variable and printed.