Home >Backend Development >Golang >How to Convert Float64 to a Fixed-Width String with Maximum Significant Digits in Go?
When presenting floating-point numbers in fixed-width tables, concerns arise regarding the preservation of significant digits. The standard fmt.Printf function offers limited control over this aspect.
To address this issue, we can implement a custom formatting function that determines the optimal number of significant digits to fit within a specified width. This involves analyzing the number in question and choosing between scientific notation and regular form based on its magnitude.
Implementation:
// format12 formats x to be 12 chars long. func format12(x float64) string { if x >= 1e12 { // For scientific notation, determine the width of the exponent. s := fmt.Sprintf("%.g", x) format := fmt.Sprintf("%%12.%dg", 12-len(s)) return fmt.Sprintf(format, x) } // For regular form, determine the width of the fraction. s := fmt.Sprintf("%.0f", x) if len(s) == 12 { return s } format := fmt.Sprintf("%%%d.%df", len(s), 12-len(s)-1) return fmt.Sprintf(format, x) }
Testing:
fs := []float64{0, 1234.567890123, 0.1234567890123, 123456789012.0, 1234567890123.0, 9.405090880450127e+9, 9.405090880450127e+19, 9.405090880450127e+119} for _, f := range fs { fmt.Println(format12(f)) }
Output:
0.0000000000 0.1234567890 1234.5678901 123456789012 1.234568e+12 9405090880.5 9.405091e+19 9.40509e+119
The above is the detailed content of How to Convert Float64 to a Fixed-Width String with Maximum Significant Digits in Go?. For more information, please follow other related articles on the PHP Chinese website!