-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfuncs.go
104 lines (98 loc) · 1.93 KB
/
funcs.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
99
100
101
102
103
104
package money
import (
"fmt"
"math/big"
"strconv"
"strings"
)
// Min returns the smallest value out of the given entries. Every debt is smaller than any credit.
// nil instances will be ignored.
func Min(m ...*Money) (*Money, error) {
var result *Money
for _, o := range m {
if o == nil {
continue
}
if result == nil {
result = o
continue
}
gt, err := result.GT(o)
if err != nil {
return nil, err
}
if gt {
result = o
}
}
return result, nil
}
// Max returns the money with the biggest value out of the given entries. Every credit is bigger than any debt.
// nil instances will be ignored.
func Max(m ...*Money) (*Money, error) {
var result *Money
for _, o := range m {
if o == nil {
continue
}
if result == nil {
result = o
continue
}
gt, err := o.GT(result)
if err != nil {
return nil, err
}
if gt {
result = o
}
}
return result, nil
}
// Sum calculates the sum of the given amounts given a common currency
func Sum(op ...*Money) (result *Money, err error) {
if len(op) < 1 {
err = ErrMissingParam
return
}
for i, o := range op {
if i == 0 {
result = o
continue
}
result, err = result.Add(o)
if err != nil {
break
}
}
return
}
func Parse(value, cur string) (*Money, error) {
c := NewCurrency(cur)
if c == nil {
return nil, ErrUnknownCurrency
}
r := new(big.Rat)
if _, err := fmt.Sscan(value, r); err != nil {
return nil, ErrInvalidSyntax
}
div := int64(1)
for i := uint(0); i < c.prec; i++ {
div = div * 10
}
r = r.Mul(r, new(big.Rat).SetFrac64(div, 1))
s := r.FloatString(0)
signedSubs, _ := strconv.ParseInt(s, 10, 64)
if signedSubs >= 0 {
return &Money{subs: uint64(signedSubs), cur: c}, nil
}
m := Money{subs: uint64(-signedSubs), cur: c}
return m.Debit(), nil
}
func ParseString(value string) (*Money, error) {
parts := strings.Split(value, " ")
if len(parts) != 2 {
return nil, ErrInvalidSyntax
}
return Parse(parts[1], parts[0])
}