forked from faridgh1991/Numero-Go
/
numero.go
executable file
·78 lines (68 loc) · 2.12 KB
/
numero.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Package numero is A micro library for converting non-english UTF8 digits. (like ۱=1, ۲=2) .
// Almost all numbers defined in Unicode is supported in Numero.
package numero
import (
"strconv"
"strings"
"unicode"
)
// zero character in different languages
var zeroStarts = [...]rune{
'0', '٠', '۰', '߀', '०', '০', '੦', '૦', '୦',
'௦', '౦', '೦', '൦', '෦', '๐', '໐', '༠', '၀',
'႐', '០', '᠐', '᥆', '᧐', '᪀', '᪐', '᭐', '᮰',
'᱀', '᱐', '꘠', '꣐', '꤀', '꧐', '꧰', '꩐', '꯰',
'0', '𐒠', '𑁦', '𑃰', '𑄶', '𑇐', '𑋰', '𑑐', '𑓐',
'𑙐', '𑛀', '𑜰', '𑣠', '𑱐', '𑵐', '𖩠', '𖭐', '𝟎',
'𝟘', '𝟢', '𝟬', '𝟶', '𞥐'}
// english zero character code
const zeroCode = 48
// Digit to check character is digit or not and if true return integer value of character
func Digit(char rune) (bool, int) {
if unicode.IsNumber(char) {
for _, zero := range zeroStarts {
if char >= zero && char <= zero+9 {
return true, int(char - zero)
}
}
}
return false, -1
}
// DigitOnly Checking if a string is all numbers
func DigitOnly(str string) bool {
for _, c := range str {
if ok, _ := Digit(c); !ok {
return false
}
}
return true
}
// Normalize to Normalize all numbers in input string
func Normalize(numberStr string) string {
return strings.Map(normalizeRune, numberStr)
}
func normalizeRune(r rune) rune {
if ok, index := Digit(r); ok {
return rune(zeroCode + index)
}
return r
}
// NormalizeAsNumber to Convert numbers to Integer or Float based on input string
func NormalizeAsNumber(numberStr string) (interface{}, error) {
if strings.Contains(numberStr, ".") {
return strconv.ParseFloat(Normalize(numberStr), 64)
}
return strconv.Atoi(Normalize(numberStr))
}
// RemoveNonDigits Strip all non numeric chars from a string
func RemoveNonDigits(str string, exceptions ...rune) string {
normalized := ""
for _, char := range str {
if ok, index := Digit(char); ok {
normalized += string(rune(zeroCode + index))
} else if len(exceptions) > 0 && exceptions[0] == char {
normalized += string(char)
}
}
return normalized
}