-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
98 lines (93 loc) · 2.17 KB
/
utils.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package money
import (
"errors"
"strconv"
"strings"
)
// IsValidStrAmount
// @Description: check if the string is a valid amount (two decimal places only)
// @Param s string
func IsValidStrAmount(s string) bool {
dotCount := 0
ddigitCount := 0
// check empty or blank string
if len(s) == 0 || s == " " || s == "" {
return false
}
for i := 0; i < len(s); i++ {
// check empty or blank string
if s[i] == ' ' {
return false
}
// check if there is more than one dot
if s[i] == '.' {
dotCount++
if dotCount > 1 {
return false
}
}
// check if there is a non-digit character
if s[i] != '.' && (s[i] < '0' || s[i] > '9') {
return false
}
if dotCount == 1 {
ddigitCount++
// check if there are more than 2 digits after the dot
// larger than 3, because the dot is counted as well
if ddigitCount > 3 {
return false
}
}
}
return true
}
func parseStrToCentsInt(s string) (int64, error) {
var decPart int64
var dolPart int64
var err error
// in case of no decimal part
if !strings.Contains(s, ".") {
// convert dollar part to cents int
dolPart, err = strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, errors.New(ErrTypeConversion)
}
} else if strings.HasPrefix(s, ".") {
// append 0 if only one digit for decimal part
if len(s[1:]) == 1 {
s += "0"
}
// convert decimal part to cents int
decPart, err = strconv.ParseInt(s[1:], 10, 64)
if err != nil {
return 0, errors.New(ErrTypeConversion)
}
} else {
// in case of dollar and decimal part
splitAmount := strings.Split(s, ".")
// append 0 if only one digit for decimal part
if len(splitAmount[1]) == 1 {
splitAmount[1] += "0"
}
// convert decimal part to cents int
decPart, err = strconv.ParseInt(splitAmount[1], 10, 64)
if err != nil {
return 0, errors.New(ErrTypeConversion)
}
// convert dollar part to cents int
dolPart, err = strconv.ParseInt(splitAmount[0], 10, 64)
if err != nil {
return 0, errors.New(ErrTypeConversion)
}
}
// calculate amount in cents
return dolPart*100 + decPart, nil
}
func isValidCurrency(currency string) bool {
switch currency {
case "USD", "EUR", "CNY":
return true
default:
return false
}
}