1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- package main
- import (
- "strconv"
- "golang.org/x/exp/slices"
- )
- // Attempts to identify if we can convert to a int
- func CanInt(text string) bool {
- negative := false
- numbers := []rune{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
- for _, c := range text {
- if !negative && c == '-' {
- negative = true
- continue
- } else if negative && c == '-' {
- return false
- }
- if !slices.Contains(numbers, c) {
- return false
- }
- }
- return true
- }
- // Attempts to identify if we can convert to a float
- //
- // Requires encountering only 1 '.', if multiple found (it's not a float), if none found (it's not a float)
- func CanFloat(text string) bool {
- found_dot := false
- negative := false
- numbers := []rune{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
- for _, c := range text {
- if !found_dot && c == '.' {
- found_dot = true
- continue
- } else if found_dot && c == '.' {
- return false
- }
- if !negative && c == '-' {
- negative = true
- continue
- } else if negative && c == '-' {
- return false
- }
- if !slices.Contains(numbers, c) {
- return false
- }
- }
- return found_dot
- }
- // https://stackoverflow.com/questions/13020308/how-to-fmt-printf-an-integer-with-thousands-comma/31046325#31046325
- //
- // This should take 1234567 and put it as 1,234,567
- func FormatCredit(n int64) string {
- in := strconv.FormatInt(n, 10)
- numOfDigits := len(in)
- if n < 0 {
- numOfDigits-- // First character is the - sign (not a digit)
- }
- numOfCommas := (numOfDigits - 1) / 3
- out := make([]byte, len(in)+numOfCommas)
- if n < 0 {
- in, out[0] = in[1:], '-'
- }
- for i, j, k := len(in)-1, len(out)-1, 0; ; i, j = i-1, j-1 {
- out[j] = in[i]
- if i == 0 {
- return string(out)
- }
- if k++; k == 3 {
- j, k = j-1, 0
- out[j] = ','
- }
- }
- }
|