bitbucket.org/ai69/amoy@v0.2.3/humanize_ftoa.go (about) 1 package amoy 2 3 // Migrate from https://github.com/dustin/go-humanize/blob/master/ftoa.go 4 5 import ( 6 "strconv" 7 "strings" 8 ) 9 10 func stripTrailingZeros(s string) string { 11 offset := len(s) - 1 12 for offset > 0 { 13 if s[offset] == '.' { 14 offset-- 15 break 16 } 17 if s[offset] != '0' { 18 break 19 } 20 offset-- 21 } 22 return s[:offset+1] 23 } 24 25 func stripTrailingDigits(s string, digits int) string { 26 if i := strings.Index(s, "."); i >= 0 { 27 if digits <= 0 { 28 return s[:i] 29 } 30 i++ 31 if i+digits >= len(s) { 32 return s 33 } 34 return s[:i+digits] 35 } 36 return s 37 } 38 39 // Ftoa converts a float to a string with no trailing zeros. 40 func Ftoa(num float64) string { 41 return stripTrailingZeros(strconv.FormatFloat(num, 'f', 6, 64)) 42 } 43 44 // FtoaWithDigits converts a float to a string but limits the resulting string 45 // to the given number of decimal places, and no trailing zeros. 46 func FtoaWithDigits(num float64, digits int) string { 47 return stripTrailingZeros(stripTrailingDigits(strconv.FormatFloat(num, 'f', 6, 64), digits)) 48 }