Documentation
¶
Overview ¶
Package currency handles currency amounts, provides currency information and formatting.
Index ¶
- Constants
- func ForCountryCode(countryCode string) (currencyCode string, ok bool)
- func GetCurrencyCodes() []string
- func GetDigits(currencyCode string) (digits uint8, ok bool)
- func GetNumericCode(currencyCode string) (numericCode string, ok bool)
- func GetSymbol(currencyCode string, locale Locale) (symbol string, ok bool)
- func IsValid(currencyCode string) bool
- func Register(currencyCode string, d Definition)
- type Amount
- func (a Amount) Add(b Amount) (Amount, error)
- func (a Amount) BigInt() *big.Int
- func (a Amount) Cmp(b Amount) (int, error)
- func (a Amount) Convert(currencyCode, rate string) (Amount, error)
- func (a Amount) CurrencyCode() string
- func (a Amount) Div(n string) (Amount, error)
- func (a Amount) Equal(b Amount) bool
- func (a Amount) Int64() (int64, error)
- func (a Amount) IsNegative() bool
- func (a Amount) IsPositive() bool
- func (a Amount) IsZero() bool
- func (a Amount) MarshalBinary() ([]byte, error)
- func (a Amount) MarshalJSON() ([]byte, error)
- func (a Amount) Mul(n string) (Amount, error)
- func (a Amount) Number() string
- func (a Amount) Round() Amount
- func (a Amount) RoundTo(digits uint8, mode RoundingMode) Amount
- func (a *Amount) Scan(src interface{}) error
- func (a Amount) String() string
- func (a Amount) Sub(b Amount) (Amount, error)
- func (a *Amount) UnmarshalBinary(data []byte) error
- func (a *Amount) UnmarshalJSON(data []byte) error
- func (a Amount) Value() (driver.Value, error)
- type Definition
- type Display
- type Formatter
- type InvalidCurrencyCodeError
- type InvalidNumberError
- type Locale
- type MismatchError
- type RoundingMode
Examples ¶
Constants ¶
const CLDRVersion = "47.0.0"
CLDRVersion is the CLDR version from which the data is derived.
const DefaultDigits uint8 = 255
DefaultDigits is a placeholder for each currency's number of fraction digits.
Variables ¶
This section is empty.
Functions ¶
func ForCountryCode ¶ added in v1.2.0
ForCountryCode returns the currency code for a country code.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
currencyCode, ok := currency.ForCountryCode("US")
fmt.Println(currencyCode, ok)
currencyCode, ok = currency.ForCountryCode("FR")
fmt.Println(currencyCode, ok)
// Non-existent country code.
_, ok = currency.ForCountryCode("XX")
fmt.Println(ok)
}
Output: USD true EUR true false
func GetCurrencyCodes ¶
func GetCurrencyCodes() []string
GetCurrencyCodes returns all known currency codes.
func GetDigits ¶
GetDigits returns the number of fraction digits for a currency code.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
digits, ok := currency.GetDigits("USD")
fmt.Println(digits, ok)
// Non-existent currency code.
digits, ok = currency.GetDigits("XXX")
fmt.Println(digits, ok)
}
Output: 2 true 0 false
func GetNumericCode ¶
GetNumericCode returns the numeric code for a currency code.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
numericCode, ok := currency.GetNumericCode("USD")
fmt.Println(numericCode, ok)
// Non-existent currency code.
numericCode, ok = currency.GetNumericCode("XXX")
fmt.Println(numericCode, ok)
}
Output: 840 true 000 false
func GetSymbol ¶
GetSymbol returns the symbol for a currency code.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
locale := currency.NewLocale("en")
symbol, ok := currency.GetSymbol("USD", locale)
fmt.Println(symbol, ok)
// Non-existent currency code.
symbol, ok = currency.GetSymbol("XXX", locale)
fmt.Println(symbol, ok)
}
Output: $ true XXX false
func IsValid ¶
IsValid checks whether a currency code is valid.
An empty currency code is considered valid.
func Register ¶ added in v1.4.0
func Register(currencyCode string, d Definition)
Register adds a currency to the internal registry.
This can be a non-ISO currency such as BTC, or an existing currency for which we want to override the predefined data.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
locale := currency.NewLocale("fr")
// Add a custom currency.
currency.Register("BTC", currency.Definition{
NumericCode: "1000",
Digits: 8,
DefaultSymbol: "₿",
})
valid := currency.IsValid("BTC")
fmt.Println(valid)
// Override an existing currency, keeping the built-in symbols.
currency.Register("AUD", currency.Definition{
NumericCode: "036",
Digits: 3,
})
digits, _ := currency.GetDigits("AUD")
symbol, _ := currency.GetSymbol("AUD", locale)
fmt.Println(digits, symbol)
// Override an existing currency and its symbols.
currency.Register("AUD", currency.Definition{
NumericCode: "036",
Digits: 3,
DefaultSymbol: "$$",
})
digits, _ = currency.GetDigits("AUD")
symbol, _ = currency.GetSymbol("AUD", locale)
fmt.Println(digits, symbol)
}
Output: true 3 $AU 3 $$
Types ¶
type Amount ¶
type Amount struct {
// contains filtered or unexported fields
}
Amount stores a decimal number with its currency code.
func NewAmount ¶
NewAmount creates a new Amount from a numeric string and a currency code.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
amount, _ := currency.NewAmount("24.49", "USD")
fmt.Println(amount)
fmt.Println(amount.Number())
fmt.Println(amount.CurrencyCode())
}
Output: 24.49 USD 24.49 USD
func NewAmountFromBigInt ¶
NewAmountFromBigInt creates a new Amount from a big.Int and a currency code.
func NewAmountFromInt64 ¶
NewAmountFromInt64 creates a new Amount from an int64 and a currency code.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
firstAmount, _ := currency.NewAmountFromInt64(2449, "USD")
secondAmount, _ := currency.NewAmountFromInt64(5000, "USD")
thirdAmount, _ := currency.NewAmountFromInt64(60, "JPY")
fmt.Println(firstAmount)
fmt.Println(secondAmount)
fmt.Println(thirdAmount)
}
Output: 24.49 USD 50.00 USD 60 JPY
func (Amount) Add ¶
Add adds a and b together and returns the result.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
firstAmount, _ := currency.NewAmount("20.99", "USD")
secondAmount, _ := currency.NewAmount("3.50", "USD")
totalAmount, _ := firstAmount.Add(secondAmount)
fmt.Println(totalAmount)
}
Output: 24.49 USD
Example (Sum) ¶
package main
import (
"fmt"
"strconv"
"github.com/bojanz/currency"
)
func main() {
// Any currency.Amount can be added to the zero value.
var sum currency.Amount
for i := 0; i <= 4; i++ {
a, _ := currency.NewAmount(strconv.Itoa(i), "AUD")
sum, _ = sum.Add(a)
}
fmt.Println(sum) // 0 + 1 + 2 + 3 + 4 = 10
}
Output: 10 AUD
func (Amount) Convert ¶
Convert converts a to a different currency.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
amount, _ := currency.NewAmount("20.99", "USD")
amount, _ = amount.Convert("EUR", "0.91")
fmt.Println(amount)
fmt.Println(amount.Round())
}
Output: 19.1009 EUR 19.10 EUR
func (Amount) CurrencyCode ¶
CurrencyCode returns the currency code.
func (Amount) Div ¶
Div divides a by n and returns the result.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
totalAmount, _ := currency.NewAmount("99.99", "USD")
amount, _ := totalAmount.Div("3")
fmt.Println(amount)
}
Output: 33.33 USD
func (Amount) Int64 ¶
Int64 returns a in minor units, as an int64. If a cannot be represented in an int64, an error is returned.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
firstAmount, _ := currency.NewAmount("24.49", "USD")
secondAmount, _ := currency.NewAmount("50", "USD")
thirdAmount, _ := currency.NewAmount("60", "JPY")
firstInt, _ := firstAmount.Int64()
secondInt, _ := secondAmount.Int64()
thirdInt, _ := thirdAmount.Int64()
fmt.Println(firstInt, secondInt, thirdInt)
}
Output: 2449 5000 60
func (Amount) IsNegative ¶
IsNegative returns whether a is negative.
func (Amount) IsPositive ¶
IsPositive returns whether a is positive.
func (Amount) MarshalBinary ¶
MarshalBinary implements the encoding.BinaryMarshaler interface.
func (Amount) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface.
func (Amount) Mul ¶
Mul multiplies a by n and returns the result.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
amount, _ := currency.NewAmount("20.99", "USD")
taxAmount, _ := amount.Mul("0.20")
fmt.Println(taxAmount)
fmt.Println(taxAmount.Round())
}
Output: 4.1980 USD 4.20 USD
func (Amount) Round ¶
Round is a shortcut for RoundTo(currency.DefaultDigits, currency.RoundHalfUp).
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
firstAmount, _ := currency.NewAmount("12.345", "USD")
secondAmount, _ := currency.NewAmount("12.345", "JPY")
fmt.Println(firstAmount.Round())
fmt.Println(secondAmount.Round())
}
Output: 12.35 USD 12 JPY
func (Amount) RoundTo ¶
func (a Amount) RoundTo(digits uint8, mode RoundingMode) Amount
RoundTo rounds a to the given number of fraction digits.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
amount, _ := currency.NewAmount("12.345", "USD")
for _, digits := range []uint8{4, 3, 2, 1, 0} {
fmt.Println(amount.RoundTo(digits, currency.RoundHalfUp))
}
}
Output: 12.3450 USD 12.345 USD 12.35 USD 12.3 USD 12 USD
func (*Amount) Scan ¶
Scan implements the database/sql.Scanner interface.
Allows scanning amounts from a PostgreSQL composite type.
func (Amount) Sub ¶
Sub subtracts b from a and returns the result.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
baseAmount, _ := currency.NewAmount("20.99", "USD")
discountAmount, _ := currency.NewAmount("5.00", "USD")
amount, _ := baseAmount.Sub(discountAmount)
fmt.Println(amount)
}
Output: 15.99 USD
Example (Diff) ¶
package main
import (
"fmt"
"strconv"
"github.com/bojanz/currency"
)
func main() {
// Any currency.Amount can be subtracted from the zero value.
var diff currency.Amount
for i := 0; i <= 4; i++ {
a, _ := currency.NewAmount(strconv.Itoa(i), "AUD")
diff, _ = diff.Sub(a)
}
fmt.Println(diff) // 0 - 1 - 2 - 3 - 4 = -10
}
Output: -10 AUD
func (*Amount) UnmarshalBinary ¶
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
func (*Amount) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface.
type Definition ¶ added in v1.4.0
type Definition struct {
// NumericCode is a three-digit code such as "999".
NumericCode string
// Digits is the number of fraction digits.
Digits uint8
// DefaultSymbol is the default symbol, used for all locales.
//
// When overriding an existing currency, keep DefaultSymbol
// empty to retain the built-in locale-specific symbols.
DefaultSymbol string
}
Definition contains information for registering a currency.
type Formatter ¶
type Formatter struct {
// AccountingStyle formats the amount using the accounting style.
// For example, "-3.00 USD" in the "en" locale is formatted as "($3.00)" instead of "-$3.00".
// Defaults to false.
AccountingStyle bool
// AddPlusSign inserts the plus sign in front of positive amounts.
// Defaults to false.
AddPlusSign bool
// NoGrouping turns off grouping of major digits.
// Defaults to false.
NoGrouping bool
// MinDigits specifies the minimum number of fraction digits.
// All zeroes past the minimum will be removed (0 => no trailing zeroes).
// Defaults to currency.DefaultDigits (e.g. 2 for USD, 0 for RSD).
MinDigits uint8
// MaxDigits specifies the maximum number of fraction digits.
// Formatted amounts will be rounded to this number of digits.
// Defaults to 6, so that most amounts are shown as-is (without rounding).
MaxDigits uint8
// RoundingMode specifies how the formatted amount will be rounded.
// Defaults to currency.RoundHalfUp.
RoundingMode RoundingMode
// CurrencyDisplay specifies how the currency will be displayed (symbol/code/none).
// Defaults to currency.DisplaySymbol.
CurrencyDisplay Display
// SymbolMap specifies custom symbols for individual currency codes.
// For example, "USD": "$" means that the $ symbol will be used even if
// the current locale's symbol is different ("US$", "$US", etc).
SymbolMap map[string]string
// contains filtered or unexported fields
}
Formatter formats and parses currency amounts.
func NewFormatter ¶
NewFormatter creates a new formatter for the given locale.
func (*Formatter) Format ¶
Format formats a currency amount.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
locale := currency.NewLocale("tr")
formatter := currency.NewFormatter(locale)
amount, _ := currency.NewAmount("1245.988", "EUR")
fmt.Println(formatter.Format(amount))
formatter.MaxDigits = 2
fmt.Println(formatter.Format(amount))
formatter.NoGrouping = true
amount, _ = currency.NewAmount("1245", "EUR")
fmt.Println(formatter.Format(amount))
formatter.MinDigits = 0
fmt.Println(formatter.Format(amount))
formatter.CurrencyDisplay = currency.DisplayNone
fmt.Println(formatter.Format(amount))
}
Output: €1.245,988 €1.245,99 €1245,00 €1245 1245
func (*Formatter) Parse ¶
Parse parses a formatted amount.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
locale := currency.NewLocale("tr")
formatter := currency.NewFormatter(locale)
amount, _ := formatter.Parse("€1.234,59", "EUR")
fmt.Println(amount)
amount, _ = formatter.Parse("EUR 1.234,59", "EUR")
fmt.Println(amount)
amount, _ = formatter.Parse("1.234,59", "EUR")
fmt.Println(amount)
}
Output: 1234.59 EUR 1234.59 EUR 1234.59 EUR
type InvalidCurrencyCodeError ¶
type InvalidCurrencyCodeError struct {
CurrencyCode string
}
InvalidCurrencyCodeError is returned when a currency code is invalid or unrecognized.
func (InvalidCurrencyCodeError) Error ¶
func (e InvalidCurrencyCodeError) Error() string
type InvalidNumberError ¶
type InvalidNumberError struct {
Number string
}
InvalidNumberError is returned when a numeric string can't be converted to a decimal.
func (InvalidNumberError) Error ¶
func (e InvalidNumberError) Error() string
type Locale ¶
Locale represents a Unicode locale identifier.
func NewLocale ¶
NewLocale creates a new Locale from its string representation.
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
firstLocale := currency.NewLocale("en-US")
fmt.Println(firstLocale)
fmt.Println(firstLocale.Language, firstLocale.Territory)
// Locale IDs are normalized.
secondLocale := currency.NewLocale("sr_rs_latn")
fmt.Println(secondLocale)
fmt.Println(secondLocale.Language, secondLocale.Script, secondLocale.Territory)
}
Output: en-US en US sr-Latn-RS sr Latn RS
func (Locale) GetParent ¶
GetParent returns the parent locale for l.
Order:
1. Language - Script - Territory (e.g. "sr-Cyrl-RS")
2. Language - Script (e.g. "sr-Cyrl")
3. Language (e.g. "sr")
4. English ("en")
5. Empty locale ("")
Note that according to CLDR rules, certain locales have special parents. For example, the parent for "es-AR" is "es-419", and for "sr-Latn" it is "en".
Example ¶
package main
import (
"fmt"
"github.com/bojanz/currency"
)
func main() {
locale := currency.NewLocale("sr-Cyrl-RS")
for {
fmt.Println(locale)
locale = locale.GetParent()
if locale.IsEmpty() {
break
}
}
}
Output: sr-Cyrl-RS sr-Cyrl sr en
func (Locale) MarshalText ¶
MarshalText implements the encoding.TextMarshaler interface.
func (*Locale) UnmarshalText ¶
UnmarshalText implements the encoding.TextUnmarshaler interface.
type MismatchError ¶
MismatchError is returned when two amounts have mismatched currency codes.
func (MismatchError) Error ¶
func (e MismatchError) Error() string
type RoundingMode ¶
type RoundingMode uint8
RoundingMode determines how the amount will be rounded.
const ( // RoundHalfUp rounds up if the next digit is >= 5. RoundHalfUp RoundingMode = iota // RoundHalfDown rounds up if the next digit is > 5. RoundHalfDown // RoundUp rounds away from 0. RoundUp // RoundDown rounds towards 0, truncating extra digits. RoundDown // RoundHalfEven rounds up if the next digit is > 5. If the next digit is equal // to 5, it rounds to the nearest even decimal. Also called bankers' rounding. RoundHalfEven )