refactoring percentage
accept any verb which is supported by AppendFloat
Vladimir Bauer
3 years ago
| 11 | 11 | type percentageType float64 |
| 12 | 12 | |
| 13 | 13 | func (s percentageType) Format(st fmt.State, verb rune) { |
| 14 | var prec int | |
| 14 | prec := -1 | |
| 15 | 15 | switch verb { |
| 16 | case 'd': | |
| 17 | case 's': | |
| 18 | prec = -1 | |
| 19 | default: | |
| 16 | case 'f', 'e', 'E': | |
| 17 | prec = 6 // default prec of fmt.Printf("%f|%e|%E") | |
| 18 | fallthrough | |
| 19 | case 'b', 'g', 'G', 'x', 'X': | |
| 20 | 20 | if p, ok := st.Precision(); ok { |
| 21 | 21 | prec = p |
| 22 | } else { | |
| 23 | prec = 6 | |
| 24 | 22 | } |
| 23 | default: | |
| 24 | verb, prec = 'f', 0 | |
| 25 | 25 | } |
| 26 | 26 | |
| 27 | b := strconv.AppendFloat(make([]byte, 0, 32), float64(s), 'f', prec, 64) | |
| 27 | b := strconv.AppendFloat(make([]byte, 0, 16), float64(s), byte(verb), prec, 64) | |
| 28 | 28 | if st.Flag(' ') { |
| 29 | 29 | b = append(b, ' ', '%') |
| 30 | 30 | } else { |
| 43 | 43 | |
| 44 | 44 | // NewPercentage percentage decorator with custom format string. |
| 45 | 45 | // |
| 46 | // `format` printf compatible verb | |
| 47 | // | |
| 48 | // `wcc` optional WC config | |
| 49 | // | |
| 46 | 50 | // format examples: |
| 47 | 51 | // |
| 52 | // format="%d" output: "1%" | |
| 53 | // format="% d" output: "1 %" | |
| 48 | 54 | // format="%.1f" output: "1.0%" |
| 49 | 55 | // format="% .1f" output: "1.0 %" |
| 50 | // format="%d" output: "1%" | |
| 51 | // format="% d" output: "1 %" | |
| 56 | // format="%f" output: "1.000000%" | |
| 57 | // format="% f" output: "1.000000 %" | |
| 52 | 58 | func NewPercentage(format string, wcc ...WC) Decorator { |
| 53 | 59 | if format == "" { |
| 54 | 60 | format = "% d" |