Home >Backend Development >Golang >How to Convert Go's Float64 to Fixed-Width, Significant-Digit-Preserving Strings?
Converting Floating-Point Numbers to Fixed-Width, Significant Digit-Preserving Strings
Question:
Is there a standard library function in Go that converts floating-point numbers (float64) to strings with a fixed width, preserving the maximum number of significant digits?
Answer:
While the Go standard library does not provide a dedicated function for this purpose, a custom solution can be implemented to achieve the desired formatting.
The approach involves branching based on the value of the float64 number. For numbers greater than or equal to 1e12, a scientific notation format is used. For numbers less than 1e12, a regular format is used.
In both cases, a preliminary formatting is performed to determine the number of fraction digits needed to fit into the desired 12-character width. The final format string is then constructed using the calculated precision.
Code Snippet:
// format12 formats x to be 12 chars long. func format12(x float64) string { if x >= 1e12 { // Check to see how many fraction digits fit in: s := fmt.Sprintf("%.g", x) format := fmt.Sprintf("%%12.%dg", 12-len(s)) return fmt.Sprintf(format, x) } // Check to see how many fraction digits fit in: 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) }
Test Cases and Output:
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 Go's Float64 to Fixed-Width, Significant-Digit-Preserving Strings?. For more information, please follow other related articles on the PHP Chinese website!