Go provides powerful formatting options for floating-point numbers using Printf()
and format specifiers.
Specifier |
Description |
Example |
%f |
Default decimal notation |
3.141593 |
%e |
Scientific notation |
3.141593e+00 |
%g |
Compact representation |
3.141593 |
Controlling Decimal Precision
package main
import "fmt"
func main() {
value := 3.14159265359
// Limiting decimal places
fmt.Printf("Two decimal places: %.2f\n", value)
fmt.Printf("Four decimal places: %.4f\n", value)
// Scientific notation with precision
fmt.Printf("Scientific (2 decimals): %.2e\n", value)
}
Width and Alignment
func formatWidthAndAlignment() {
price := 42.5678
// Right-aligned with total width
fmt.Printf("Width 10: %10.2f\n", price)
// Left-aligned with total width
fmt.Printf("Left-aligned: %-10.2f\n", price)
}
graph TD
A[Float Value] --> B{Formatting Decision}
B --> |Precision| C[Decimal Places]
B --> |Notation| D[Fixed/Scientific]
B --> |Alignment| E[Left/Right]
import (
"fmt"
"strconv"
)
func advancedFormatting() {
// Convert float to string with specific formatting
value := 123.456
formatted := strconv.FormatFloat(value, 'f', 2, 64)
fmt.Println(formatted)
}
- Use
Printf()
for debugging and logging
- Prefer
strconv.FormatFloat()
for performance-critical code
- Choose appropriate precision based on use case
LabEx Insight
LabEx recommends practicing these formatting techniques to develop a nuanced understanding of float representation and display.