When working with floating-point numbers in Go, it's important to understand how to format and print them effectively. Go provides several options for formatting and printing floating-point values, allowing you to control the output precision and presentation.
One of the most common ways to print floating-point values is using the fmt.Println()
function. By default, fmt.Println()
will use the default formatting for floating-point numbers, which can sometimes result in unexpected output:
package main
import "fmt"
func main() {
f32 := 3.14159
f64 := 6.02214076e23
fmt.Println("float32 value:", f32)
fmt.Println("float64 value:", f64)
}
This will output:
float32 value: 3.14159
float64 value: 6.022140800000001e+23
To have more control over the formatting, you can use the fmt.Printf()
function and its various formatting verbs, such as %f
, %e
, and %g
. These verbs allow you to specify the precision, width, and other formatting options for the floating-point output:
package main
import "fmt"
func main() {
f32 := 3.14159
f64 := 6.02214076e23
fmt.Printf("float32 value: %.2f\n", f32)
fmt.Printf("float64 value: %.2e\n", f64)
}
This will output:
float32 value: 3.14
float64 value: 6.02e+23
By using the appropriate formatting verbs and options, you can control the precision, scientific notation, and other aspects of how floating-point values are displayed in your Go programs.