Home > Backend Development > Golang > How to Convert Float64 to a Fixed-Width String with Maximum Significant Digits in Go?

How to Convert Float64 to a Fixed-Width String with Maximum Significant Digits in Go?

Linda Hamilton
Release: 2024-12-05 15:46:10
Original
850 people have browsed it

How to Convert Float64 to a Fixed-Width String with Maximum Significant Digits in Go?

Converting Float64 to String with Fixed Width and Maximum Significant Digits

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.

Solution: Custom Formatting

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)
}
Copy after login

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))
}
Copy after login

Output:

0.0000000000
0.1234567890
1234.5678901
123456789012
1.234568e+12
9405090880.5
9.405091e+19
9.40509e+119
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template