-
Notifications
You must be signed in to change notification settings - Fork 13
/
price.go
69 lines (51 loc) · 1.34 KB
/
price.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
package helper
import (
"fmt"
"github.com/bojanz/currency"
)
const (
unit = 1000
)
type Price int64
func (c Price) Float() float64 {
return float64(c) / unit
}
func (c Price) Units() int64 {
return int64(c)
}
func (c Price) String() string {
return fmt.Sprintf("%.2f", c.Float())
}
func (c Price) StringWithCurrency(currencySymbol string) string {
return fmt.Sprintf("%.2f "+currencySymbol, c.Float())
}
func (c Price) StringByLocale(locale, inCurrency string) (string, error) {
amount, err := currency.NewAmount(c.String(), inCurrency)
if err != nil {
return "", err
}
return currency.NewFormatter(currency.NewLocale(locale)).Format(amount), nil
}
func NewPrice(amount float64) Price {
return Price(amount * unit)
}
func NewTotalPrice(amount float64, quantity uint64) Price {
return NewPrice(float64(NewPrice(amount).Units()*int64(quantity)) / unit)
}
func GetPriceDTO(priceValue float64, priceCurrencyISO4217, countryCodeAlpha2 string) *DTOPrice {
price := NewPrice(priceValue)
priceWithCurrency, err := price.StringByLocale(countryCodeAlpha2, priceCurrencyISO4217)
if err != nil {
panic(err)
}
return &DTOPrice{
Price: price.Float(),
PriceString: price.String(),
PriceWithCurrency: priceWithCurrency,
}
}
type DTOPrice struct {
Price float64
PriceString string
PriceWithCurrency string
}