github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/ss/float.go (about)

     1  package ss
     2  
     3  import "strconv"
     4  
     5  // FormatFloat format a float64 to a string with the fewest digits necessary.
     6  func FormatFloat(f float64) string {
     7  	// The -1 as the 3rd parameter tells the func to print the fewest digits necessary to accurately represent the float.
     8  	// See here: https://golang.org/pkg/strconv/#FormatFloat
     9  	return strconv.FormatFloat(f, 'f', -1, 64)
    10  }
    11  
    12  type FormatFloatOptionConfig struct {
    13  	// Prec controls the number of digits (excluding the exponent)
    14  	// printed by the 'e', 'E', 'f', 'g', 'G', 'x', and 'X' formats.
    15  	// For 'e', 'E', 'f', 'x', and 'X', it is the number of digits after the decimal point.
    16  	// For 'g' and 'G' it is the maximum number of significant digits (trailing zeros are removed).
    17  	// The special precision -1 uses the smallest number of digits
    18  	Prec                int
    19  	RemoveTrailingZeros bool
    20  }
    21  
    22  type FormatFloatOptionConfigFn func(*FormatFloatOptionConfig)
    23  
    24  func WithRemoveTrailingZeros(yes bool) FormatFloatOptionConfigFn {
    25  	return func(c *FormatFloatOptionConfig) {
    26  		c.RemoveTrailingZeros = yes
    27  	}
    28  }
    29  
    30  func WithPrec(prec int) FormatFloatOptionConfigFn {
    31  	return func(c *FormatFloatOptionConfig) {
    32  		c.Prec = prec
    33  	}
    34  }
    35  
    36  func FormatFloatOption(f float64, fns ...FormatFloatOptionConfigFn) string {
    37  	c := &FormatFloatOptionConfig{Prec: -1}
    38  	for _, fn := range fns {
    39  		fn(c)
    40  	}
    41  
    42  	b := strconv.FormatFloat(f, 'f', c.Prec, 64)
    43  	if c.RemoveTrailingZeros && c.Prec != 0 {
    44  		i := len(b) - 1
    45  		for ; i >= 0; i-- {
    46  			if b[i] != '0' {
    47  				if b[i] != '.' {
    48  					i++
    49  				}
    50  				break
    51  			}
    52  		}
    53  
    54  		b = b[:i]
    55  	}
    56  
    57  	return b
    58  }