ftoa.go 936 B

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