-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathconvert.go
43 lines (32 loc) · 797 Bytes
/
convert.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
package handy
import (
"strconv"
"strings"
)
// StringAsFloat tries to convert a string to float, and if it can't, just returns zero
// It's limited to one billion
func StringAsFloat(s string, decimalSeparator, thousandsSeparator rune) float64 {
if s == "" {
return 0.0
}
const maxLength = 20
if len([]rune(s)) > maxLength {
s = s[0:maxLength]
}
s = strings.Replace(s, string(thousandsSeparator), "", -1)
s = strings.Replace(s, string(decimalSeparator), ".", -1)
if f, err := strconv.ParseFloat(s, 64); err == nil {
return f
}
return 0.0
}
// StringAsInteger returns the integer value extracted from string, or zero
func StringAsInteger(s string) int {
if s == "" {
return 0
}
if i, err := strconv.ParseInt(s, 10, 32); err == nil {
return int(i)
}
return 0
}