|
1
|
|
|
package money |
|
2
|
|
|
|
|
3
|
|
|
import ( |
|
4
|
|
|
"strconv" |
|
5
|
|
|
"strings" |
|
6
|
|
|
) |
|
7
|
|
|
|
|
8
|
|
|
// Currency represents the currency information for formatting |
|
9
|
|
|
type Currency struct { |
|
10
|
|
|
code string |
|
11
|
|
|
decimalDelimiter string |
|
12
|
|
|
thousandDelimiter string |
|
13
|
|
|
exponent int |
|
14
|
|
|
symbol string |
|
15
|
|
|
template string |
|
16
|
|
|
} |
|
17
|
|
|
|
|
18
|
|
|
// https://en.wikipedia.org/wiki/ISO_4217 |
|
19
|
|
|
|
|
20
|
|
|
// USD creates and returns a new Currency instance for USD |
|
21
|
|
|
func USD() *Currency { |
|
22
|
1 |
|
return &Currency{code: "USD", decimalDelimiter: ".", thousandDelimiter: ",", exponent: 2, symbol: "$", template: "$1"} |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
// EUR creates and returns a new Currency instance for EUR |
|
26
|
|
|
func EUR() *Currency { |
|
27
|
1 |
|
return &Currency{code: "EUR", decimalDelimiter: ",", thousandDelimiter: ".", exponent: 2, symbol: "€", template: "$1"} |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
// Add creates and returns a new Currency instance |
|
31
|
|
|
func Add(code string, decimalDelimiter string, thousandDelimiter string, exponent int, symbol string, template string) *Currency { |
|
32
|
1 |
|
return &Currency{ |
|
33
|
|
|
code: code, |
|
34
|
|
|
decimalDelimiter: decimalDelimiter, |
|
35
|
|
|
thousandDelimiter: thousandDelimiter, |
|
36
|
|
|
exponent: exponent, |
|
37
|
|
|
symbol: symbol, |
|
38
|
|
|
template: template, |
|
39
|
|
|
} |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
// Format returns a formatted string for the given amount value |
|
43
|
|
|
func (c *Currency) Format(amount int64) string { |
|
44
|
1 |
|
positiveAmount := amount |
|
45
|
1 |
|
if amount < 0 { |
|
46
|
1 |
|
positiveAmount = amount * -1 |
|
47
|
|
|
} |
|
48
|
1 |
|
result := strconv.FormatInt(positiveAmount, 10) |
|
49
|
|
|
|
|
50
|
1 |
|
if len(result) <= c.exponent { |
|
51
|
1 |
|
result = strings.Repeat("0", c.exponent-len(result)+1) + result |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
1 |
|
if c.thousandDelimiter != "" { |
|
55
|
1 |
|
for i := len(result) - c.exponent - 3; i > 0; i -= 3 { |
|
56
|
1 |
|
result = result[:i] + c.thousandDelimiter + result[i:] |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
1 |
|
if c.exponent > 0 { |
|
61
|
1 |
|
result = result[:len(result)-c.exponent] + c.decimalDelimiter + result[len(result)-c.exponent:] |
|
62
|
|
|
} |
|
63
|
1 |
|
result = strings.Replace(c.template, "1", result, 1) |
|
64
|
1 |
|
result = strings.Replace(result, "$", c.symbol, 1) |
|
65
|
|
|
|
|
66
|
|
|
// Add minus sign for negative amount |
|
67
|
1 |
|
if amount < 0 { |
|
68
|
1 |
|
result = "-" + result |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
1 |
|
return result |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
func (c *Currency) equals(currency *Currency) bool { |
|
75
|
1 |
|
return c.code == currency.code |
|
76
|
|
|
} |
|
77
|
|
|
|