-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmoney.go
More file actions
88 lines (74 loc) · 2.04 KB
/
money.go
File metadata and controls
88 lines (74 loc) · 2.04 KB
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
package money
import "math"
// Money represents a monetary value stored in minor units
// (for example cents) to avoid floating point errors.
type Money struct {
amount uint64
}
// New creates a new Money value from minor units.
func New(minor uint64) Money {
return Money{amount: minor}
}
// Minor returns the value in minor units.
func (m Money) Minor() uint64 {
return m.amount
}
// Add returns a new Money with the sum of two values.
func (m Money) Add(other Money) Money {
return Money{
amount: m.amount + other.amount,
}
}
// Sub subtracts the other value.
// It panics if the result would be negative.
func (m Money) Sub(other Money) Money {
if other.amount > m.amount {
panic("money: subtraction would result in negative value")
}
return Money{
amount: m.amount - other.amount,
}
}
// Mul multiplies the amount by a floating-point factor.
// The result is always rounded down to the nearest minor unit.
func (m Money) Mul(factor float64) Money {
if factor < 0 {
panic("money: negative multiplier")
}
return Money{
amount: uint64(math.Floor(float64(m.amount) * factor)),
}
}
// Split divides the money amount into n parts.
// The split is exact: the sum of all parts equals the original amount.
// Any remainder is distributed by adding 1 minor unit to the first parts.
func (m Money) Split(n int) []Money {
if n <= 0 {
panic("money: split count must be positive")
}
base := m.amount / uint64(n)
rem := m.amount % uint64(n)
out := make([]Money, n)
for i := range n {
amt := base
if uint64(i) < rem {
amt++
}
out[i] = Money{amount: amt}
}
return out
}
// IsZero checks if the money value is zero.
func (m Money) IsZero() bool {
return m.amount == 0
}
// CurrencyAdapter defines how to convert minor units
// into major units for a specific currency.
type CurrencyAdapter interface {
MinorToMajor(minor uint64) float64
}
// ToMajorUnits converts the money value to major units
// using the provided currency adapter.
func (m Money) ToMajorUnits(adapter CurrencyAdapter) float64 {
return adapter.MinorToMajor(m.amount)
}