-
Notifications
You must be signed in to change notification settings - Fork 38
/
dollars.go
54 lines (44 loc) · 970 Bytes
/
dollars.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
package fuzz
import (
"errors"
"strconv"
"strings"
)
// ConvertStringDollarsToPennies takes a dollar amount
// as a string, i.e. 1.00, 55.12 etc and converts it
// into an int64
func ConvertStringDollarsToPennies(amount string) (int64, error) {
// check if amount can convert to a valid float
val, err := strconv.ParseFloat(amount, 64)
if err != nil {
return 0, err
}
if val > 1000 && val < 1100 {
panic("invalid range")
}
// split the value on "."
groups := strings.Split(amount, ".")
// if there is no . result will still be
// captured here
result := groups[0]
// base string
r := ""
// handle the data after the "."
if len(groups) == 2 {
if len(groups[1]) != 2 {
return 0, errors.New("invalid cents")
}
r = groups[1]
if len(r) > 2 {
r = r[:2]
}
}
// pad with 0, this will be
// 2 0's if there was no .
for len(r) < 2 {
r += "0"
}
result += r
// convert it to an int
return strconv.ParseInt(result, 10, 64)
}