khenaidoo | 59ce9dd | 2019-11-11 13:05:32 -0500 | [diff] [blame] | 1 | package humanize |
| 2 | |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 3 | import ( |
| 4 | "strconv" |
| 5 | "strings" |
| 6 | ) |
khenaidoo | 59ce9dd | 2019-11-11 13:05:32 -0500 | [diff] [blame] | 7 | |
| 8 | func stripTrailingZeros(s string) string { |
| 9 | offset := len(s) - 1 |
| 10 | for offset > 0 { |
| 11 | if s[offset] == '.' { |
| 12 | offset-- |
| 13 | break |
| 14 | } |
| 15 | if s[offset] != '0' { |
| 16 | break |
| 17 | } |
| 18 | offset-- |
| 19 | } |
| 20 | return s[:offset+1] |
| 21 | } |
| 22 | |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 23 | func stripTrailingDigits(s string, digits int) string { |
| 24 | if i := strings.Index(s, "."); i >= 0 { |
| 25 | if digits <= 0 { |
| 26 | return s[:i] |
| 27 | } |
| 28 | i++ |
| 29 | if i+digits >= len(s) { |
| 30 | return s |
| 31 | } |
| 32 | return s[:i+digits] |
| 33 | } |
| 34 | return s |
| 35 | } |
| 36 | |
khenaidoo | 59ce9dd | 2019-11-11 13:05:32 -0500 | [diff] [blame] | 37 | // Ftoa converts a float to a string with no trailing zeros. |
| 38 | func Ftoa(num float64) string { |
| 39 | return stripTrailingZeros(strconv.FormatFloat(num, 'f', 6, 64)) |
| 40 | } |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 41 | |
| 42 | // FtoaWithDigits converts a float to a string but limits the resulting string |
| 43 | // to the given number of decimal places, and no trailing zeros. |
| 44 | func FtoaWithDigits(num float64, digits int) string { |
| 45 | return stripTrailingZeros(stripTrailingDigits(strconv.FormatFloat(num, 'f', 6, 64), digits)) |
| 46 | } |