utils.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package main
  2. import (
  3. "strconv"
  4. "golang.org/x/exp/slices"
  5. )
  6. // Attempts to identify if we can convert to a int
  7. func CanInt(text string) bool {
  8. negative := false
  9. numbers := []rune{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
  10. for _, c := range text {
  11. if !negative && c == '-' {
  12. negative = true
  13. continue
  14. } else if negative && c == '-' {
  15. return false
  16. }
  17. if !slices.Contains(numbers, c) {
  18. return false
  19. }
  20. }
  21. return true
  22. }
  23. // Attempts to identify if we can convert to a float
  24. //
  25. // Requires encountering only 1 '.', if multiple found (it's not a float), if none found (it's not a float)
  26. func CanFloat(text string) bool {
  27. found_dot := false
  28. negative := false
  29. numbers := []rune{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
  30. for _, c := range text {
  31. if !found_dot && c == '.' {
  32. found_dot = true
  33. continue
  34. } else if found_dot && c == '.' {
  35. return false
  36. }
  37. if !negative && c == '-' {
  38. negative = true
  39. continue
  40. } else if negative && c == '-' {
  41. return false
  42. }
  43. if !slices.Contains(numbers, c) {
  44. return false
  45. }
  46. }
  47. return found_dot
  48. }
  49. // https://stackoverflow.com/questions/13020308/how-to-fmt-printf-an-integer-with-thousands-comma/31046325#31046325
  50. //
  51. // This should take 1234567 and put it as 1,234,567
  52. func FormatCredit(n int64) string {
  53. in := strconv.FormatInt(n, 10)
  54. numOfDigits := len(in)
  55. if n < 0 {
  56. numOfDigits-- // First character is the - sign (not a digit)
  57. }
  58. numOfCommas := (numOfDigits - 1) / 3
  59. out := make([]byte, len(in)+numOfCommas)
  60. if n < 0 {
  61. in, out[0] = in[1:], '-'
  62. }
  63. for i, j, k := len(in)-1, len(out)-1, 0; ; i, j = i-1, j-1 {
  64. out[j] = in[i]
  65. if i == 0 {
  66. return string(out)
  67. }
  68. if k++; k == 3 {
  69. j, k = j-1, 0
  70. out[j] = ','
  71. }
  72. }
  73. }