github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/ztype/decimal.go (about) 1 package ztype 2 3 import ( 4 "math" 5 "strconv" 6 "strings" 7 ) 8 9 var tenToAny = [...]string{0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", 16: "g", 17: "h", 18: "i", 19: "j", 20: "k", 21: "l", 22: "m", 23: "n", 24: "o", 25: "p", 26: "q", 27: "r", 28: "s", 29: "t", 30: "u", 31: "v", 32: "w", 33: "x", 34: "y", 35: "z", 36: "A", 37: "B", 38: "C", 39: "D", 40: "E", 41: "F", 42: "G", 43: "H", 44: "I", 45: "J", 46: "K", 47: "L", 48: "M", 49: "N", 50: "O", 51: "P", 52: "Q", 53: "R", 54: "S", 55: "T", 56: "U", 57: "V", 58: "W", 59: "X", 60: "Y", 61: "Z", 62: "_", 63: "-", 64: "|", 65: "<"} 10 11 // DecimalToAny Convert decimal to arbitrary decimal values 12 func DecimalToAny(value, base int) (newNumStr string) { 13 if base < 2 { 14 return 15 } 16 if base <= 32 { 17 return strconv.FormatInt(int64(value), base) 18 } 19 var ( 20 remainder int 21 remainderString string 22 ) 23 for value != 0 { 24 remainder = value % base 25 if remainder < 66 && remainder > 9 { 26 remainderString = tenToAny[remainder] 27 } else { 28 remainderString = strconv.FormatInt(int64(remainder), 10) 29 } 30 newNumStr = remainderString + newNumStr 31 value = value / base 32 } 33 return 34 } 35 36 // AnyToDecimal Convert arbitrary decimal values to decimal 37 func AnyToDecimal(value string, base int) (v int) { 38 if base < 2 { 39 return 40 } 41 if base <= 32 { 42 n, _ := strconv.ParseInt(value, base, 64) 43 v = int(n) 44 return 45 } 46 n := 0.0 47 nNum := len(strings.Split(value, "")) - 1 48 for _, v := range strings.Split(value, "") { 49 tmp := float64(findKey(v)) 50 if tmp != -1 { 51 n = n + tmp*math.Pow(float64(base), float64(nNum)) 52 nNum = nNum - 1 53 } else { 54 break 55 } 56 } 57 v = int(n) 58 return 59 } 60 61 func findKey(in string) int { 62 result := -1 63 for k, v := range tenToAny { 64 if in == v { 65 result = k 66 } 67 } 68 return result 69 }