-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcurrency.go
76 lines (63 loc) · 2.02 KB
/
currency.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
package money
import (
"strconv"
"strings"
)
// Currency represents the currency information for formatting
type Currency struct {
code string
decimalDelimiter string
thousandDelimiter string
exponent int
symbol string
template string
}
// https://en.wikipedia.org/wiki/ISO_4217
// USD creates and returns a new Currency instance for USD
func USD() *Currency {
return &Currency{code: "USD", decimalDelimiter: ".", thousandDelimiter: ",", exponent: 2, symbol: "$", template: "$1"}
}
// EUR creates and returns a new Currency instance for EUR
func EUR() *Currency {
return &Currency{code: "EUR", decimalDelimiter: ",", thousandDelimiter: ".", exponent: 2, symbol: "€", template: "$1"}
}
// Add creates and returns a new Currency instance
func Add(code string, decimalDelimiter string, thousandDelimiter string, exponent int, symbol string, template string) *Currency {
return &Currency{
code: code,
decimalDelimiter: decimalDelimiter,
thousandDelimiter: thousandDelimiter,
exponent: exponent,
symbol: symbol,
template: template,
}
}
// Format returns a formatted string for the given amount value
func (c *Currency) Format(amount int64) string {
positiveAmount := amount
if amount < 0 {
positiveAmount = amount * -1
}
result := strconv.FormatInt(positiveAmount, 10)
if len(result) <= c.exponent {
result = strings.Repeat("0", c.exponent-len(result)+1) + result
}
if c.thousandDelimiter != "" {
for i := len(result) - c.exponent - 3; i > 0; i -= 3 {
result = result[:i] + c.thousandDelimiter + result[i:]
}
}
if c.exponent > 0 {
result = result[:len(result)-c.exponent] + c.decimalDelimiter + result[len(result)-c.exponent:]
}
result = strings.Replace(c.template, "1", result, 1)
result = strings.Replace(result, "$", c.symbol, 1)
// Add minus sign for negative amount
if amount < 0 {
result = "-" + result
}
return result
}
func (c *Currency) equals(currency *Currency) bool {
return c.code == currency.code
}