README
¶
Money
Package money implements immutable monetary amounts for Go.
Getting started
To install the money package into your Go workspace, you can use the go get command:
go get github.com/govalues/money
To use the money package in your Go project, you can import it as follows:
import (
"github.com/govalues/decimal"
"github.com/govalues/money"
)
Using Amount
To create a new amount, you can use one of the provided constructors,
such as NewAmount
, ParseAmount
or MustParseAmount
.
d := decimal.New(12345, 2) // d = 123.45
a, _ := money.NewAmount(money.USD, d) // a = USD 123.45
b := money.MustParseAmount("USD", "123.45") // b = USD 123.45
Once you have an amount, you can perform arithmetic operations such as addition, subtraction, multiplication, division, as well as rounding operations such as ceiling, floor, truncation, and rounding.
sum := a.Add(b)
difference := a.Sub(b)
product := a.Mul(d)
quotient := a.Quo(d)
ratio := a.Rat(b)
ceil := a.Ceil(2)
floor := a.Floor(2)
trunc := a.Trunc(2)
round := a.Round(2)
For more details on these and other methods, see the package documentation at pkg.go.dev.
Benchmarks
For the benchmark results please check description of decimal package.
Contributing to the project
The money package is hosted on GitHub. To contribute to the project, follow these steps:
- Fork the repository and clone it to your local machine.
- Make the desired changes to the code.
- Write tests for the changes you made.
- Ensure that all tests pass by running
go test
. - Commit the changes and push them to your fork.
- Submit a pull request with a clear description of the changes you made.
- Wait for the maintainers to review and merge your changes.
Note: Before making any significant changes to the code, it is recommended to open an issue to discuss the proposed changes with the maintainers. This will help to ensure that the changes align with the project's goals and roadmap.
Documentation
¶
Overview ¶
Package money implements immutable monetary values in various currencies. It leverages the capabilities of decimal.Decimal for handling decimal floating-point numbers and combines them with a Currency to represent different currencies.
Features ¶
- Immutable monetary values, ensuring safe usage across multiple goroutines
- Support for various currencies and their corresponding scales
- Arithmetic and comparison operations between monetary values
- Conversion of monetary values using exchange rates
Supported Ranges ¶
The range of monetary values supported refer to the Supported Ranges section of the decimal package description.
Operations ¶
The package provides various arithmetic and comparison operations for monetary values, such as Add, Sub, Mul, FMA, Quo, and Rat. It also supports splitting an amount into equal parts and converting between different currencies using exchange rates.
Rounding ¶
The package allows for rounding monetary values using several methods, including Ceil, Floor, Trunc, and Round.
Example (EffectiveRate) ¶
This example calculates the effective interest rate for a 10% nominal interest rate compounded monthly on a USD 10,000 balance.
Output: Nominal Rate = 10.00%, Effective Rate = 10.4713% Month Days Incoming Interest Outgoing 1 31 10000.00 +84.93 10084.93 2 28 10084.93 +77.36 10162.29 3 31 10162.29 +86.31 10248.60 4 30 10248.60 +84.24 10332.84 5 31 10332.84 +87.76 10420.60 6 30 10420.60 +85.65 10506.25 7 31 10506.25 +89.23 10595.48 8 31 10595.48 +89.99 10685.47 9 30 10685.47 +87.83 10773.30 10 31 10773.30 +91.50 10864.80 11 30 10864.80 +89.30 10954.10 12 31 10954.10 +93.03 11047.13 Total +1047.13
Example (LoanAmortization) ¶
In this example, a loan amortization table is generated for a loan with an initial amount of USD 12,000, an annual interest rate of 10%, and a repayment period of 1 year.
Output: Initial Amount = USD 12000.00, Interest Rate = 10.00% Month Repayment Principal Interest Outstanding 1 1054.99 954.99 100.00 11045.01 2 1054.99 962.95 92.04 10082.06 3 1054.99 970.97 84.02 9111.09 4 1054.99 979.06 75.93 8132.03 5 1054.99 987.22 67.77 7144.81 6 1054.99 995.45 59.54 6149.36 7 1054.99 1003.75 51.24 5145.61 8 1054.99 1012.11 42.88 4133.49 9 1054.99 1020.54 34.45 3112.95 10 1054.99 1029.05 25.94 2083.90 11 1054.99 1037.62 17.37 1046.28 12 1054.99 1046.27 8.72 0.01 Total 12659.89 11999.99 659.90
Example (TaxCalculation) ¶
In this example, the sales tax amount is calculated for a product with a given price after tax, using a specified tax rate.
Output: Price (before tax) = USD 9.39 Tax Rate = 6.5% Sales Tax = USD 0.61 Price (after tax) = USD 10.00
Index ¶
- type Amount
- func (a Amount) Abs() Amount
- func (a Amount) Add(b Amount) Amount
- func (a Amount) Ceil(scale int) Amount
- func (a Amount) CeilToCurr() Amount
- func (a Amount) Cmp(b Amount) int
- func (a Amount) CmpTotal(b Amount) int
- func (a Amount) Coef() uint64
- func (a Amount) CopySign(b Amount) Amount
- func (a Amount) Curr() Currency
- func (a Amount) FMA(e decimal.Decimal, b Amount) Amount
- func (a Amount) Float64() (f float64, ok bool)
- func (a Amount) Floor(scale int) Amount
- func (a Amount) FloorToCurr() Amount
- func (a Amount) Format(state fmt.State, verb rune)
- func (a Amount) Int64() (i int64, f int64, ok bool)
- func (a Amount) IsInt() bool
- func (a Amount) IsNeg() bool
- func (a Amount) IsOne() bool
- func (a Amount) IsPos() bool
- func (a Amount) IsZero() bool
- func (a Amount) Max(b Amount) Amount
- func (a Amount) Min(b Amount) Amount
- func (a Amount) MinorUnits() (m int64, ok bool)
- func (a Amount) Mul(e decimal.Decimal) Amount
- func (a Amount) Neg() Amount
- func (a Amount) One() Amount
- func (a Amount) Prec() int
- func (a Amount) Quantize(b Amount) Amount
- func (a Amount) Quo(e decimal.Decimal) Amount
- func (a Amount) Rat(b Amount) decimal.Decimal
- func (a Amount) Reduce() Amount
- func (a Amount) Round(scale int) Amount
- func (a Amount) RoundToCurr() Amount
- func (a Amount) SameCurr(b Amount) bool
- func (a Amount) SameScale(b Amount) bool
- func (a Amount) SameScaleAsCurr() bool
- func (a Amount) Scale() int
- func (a Amount) Sign() int
- func (a Amount) Split(n int) []Amount
- func (a Amount) String() string
- func (a Amount) Sub(b Amount) Amount
- func (a Amount) Trunc(scale int) Amount
- func (a Amount) TruncToCurr() Amount
- func (a Amount) ULP() Amount
- func (a Amount) WithinOne() bool
- func (a Amount) Zero() Amount
- type Currency
- type ExchangeRate
- func (r ExchangeRate) Base() Currency
- func (r ExchangeRate) CanConv(b Amount) bool
- func (r ExchangeRate) Conv(b Amount) Amount
- func (r ExchangeRate) Format(state fmt.State, verb rune)
- func (r ExchangeRate) Inv() ExchangeRate
- func (r ExchangeRate) IsOne() bool
- func (r ExchangeRate) IsZero() bool
- func (r ExchangeRate) Mul(e decimal.Decimal) ExchangeRate
- func (r ExchangeRate) Prec() int
- func (r ExchangeRate) Quote() Currency
- func (r ExchangeRate) Round(scale int) ExchangeRate
- func (r ExchangeRate) RoundToCurr() ExchangeRate
- func (r ExchangeRate) SameCurr(q ExchangeRate) bool
- func (r ExchangeRate) SameScale(q ExchangeRate) bool
- func (r ExchangeRate) SameScaleAsCurr() bool
- func (r ExchangeRate) Scale() int
- func (r ExchangeRate) String() string
- func (r ExchangeRate) WithinOne() bool
Examples ¶
- Package (EffectiveRate)
- Package (LoanAmortization)
- Package (TaxCalculation)
- Amount.Abs
- Amount.Add
- Amount.Ceil
- Amount.CeilToCurr
- Amount.Cmp
- Amount.CmpTotal
- Amount.Coef
- Amount.CopySign
- Amount.Curr
- Amount.FMA
- Amount.Float64
- Amount.Floor
- Amount.FloorToCurr
- Amount.Format
- Amount.Int64
- Amount.IsInt
- Amount.IsNeg
- Amount.IsOne
- Amount.IsPos
- Amount.IsZero
- Amount.Max
- Amount.Min
- Amount.MinorUnits
- Amount.Mul
- Amount.Neg
- Amount.One
- Amount.Prec
- Amount.Quantize
- Amount.Quo
- Amount.Rat
- Amount.Reduce
- Amount.Round
- Amount.RoundToCurr
- Amount.SameCurr
- Amount.SameScale
- Amount.SameScaleAsCurr
- Amount.Scale
- Amount.Sign
- Amount.Split
- Amount.String
- Amount.Sub
- Amount.Trunc
- Amount.TruncToCurr
- Amount.ULP
- Amount.WithinOne
- Amount.Zero
- Currency.Code
- Currency.Format
- Currency.MarshalText
- Currency.Num
- Currency.Scale
- Currency.String
- Currency.UnmarshalText
- ExchangeRate.Base
- ExchangeRate.CanConv
- ExchangeRate.Conv
- ExchangeRate.Format
- ExchangeRate.Inv
- ExchangeRate.IsOne
- ExchangeRate.IsZero
- ExchangeRate.Mul
- ExchangeRate.Prec
- ExchangeRate.Quote
- ExchangeRate.Round
- ExchangeRate.RoundToCurr
- ExchangeRate.SameCurr
- ExchangeRate.SameScale
- ExchangeRate.SameScaleAsCurr
- ExchangeRate.Scale
- ExchangeRate.String
- ExchangeRate.WithinOne
- MustParseAmount
- MustParseCurr
- MustParseExchRate
- NewAmount
- NewAmount (Iso8583)
- NewAmount (Protobuf)
- NewAmount (Stripe)
- NewExchRate
- ParseAmount
- ParseCurr
- ParseExchRate
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Amount ¶
type Amount struct {
// contains filtered or unexported fields
}
Amount type represents a monetary amount. The zero value corresponds to "XXX 0", where XXX indicates an unknown currency. This type is designed to be safe for concurrent use by multiple goroutines.
func MustParseAmount ¶
MustParseAmount is like ParseAmount but panics if any of the strings cannot be parsed. This function simplifies safe initialization of global variables holding amounts.
func NewAmount ¶
NewAmount returns a new amount with the specified currency and value. If the scale of the amount is less than the scale of the currency, the result will be zero-padded to the right.
Example (Iso8583) ¶
In this example, we parse the string "840D000000001234", which represents -12.34 USD, according to the specification for "DE54, Additional Amounts" in ISO 8583.
Output: USD -12.34
Example (Protobuf) ¶
This is an example of how to a parse a monetary amount formatted as MoneyProto.
Output: USD -12.34
Example (Stripe) ¶
This is an example of how to a parse a monetary amount formatted according to Stripe API specification.
Output: USD -12.34
func ParseAmount ¶
ParseAmount converts currency and decimal strings to (possibly rounded) amount. See also methods ParseCurr and decimal.Parse.
func (Amount) Add ¶
Add returns the (possibly rounded) sum of amounts a and b.
Add panics if:
- amounts are denominated in different currencies. To avoid this panic, use Amount.SameCurr to verify that both amounts have the same currency before calling Add.
- the integer part of the result exceeds the maximum precision allowed by the currency. This limit is calculated as (decimal.MaxPrec - a.Curr().Scale()). For example, when dealing with US Dollars, Add will panic if the integer part of the result has more than 17 digits (19 - 2 = 17).
func (Amount) Ceil ¶
Ceil returns an amount rounded up to the specified number of digits after the decimal point. If the scale of the amount is less than the specified scale, the result will be zero-padded to the right. If the specified scale is less than the scale of the currency, the amount will be rounded up to the scale of te currency instead. See also method Amount.CeilToCurr.
Ceil panics if the integer part of the result exceeds the maximum precision, calculated as (decimal.MaxPrec - scale).
func (Amount) CeilToCurr ¶
CeilToCurr returns an amount rounded up to the scale of its currency. See also method Amount.SameScaleAsCurr.
func (Amount) Cmp ¶
Cmp compares amounts numerically and returns:
-1 if a < b 0 if a == b +1 if a > b
Cmp panics if amounts are denominated in different currencies. To avoid this panic, use Amount.SameCurr to verify that both amounts have the same currency before calling Cmp.
func (Amount) CmpTotal ¶
CmpTotal compares the representation of amounts and returns:
-1 if a < b -1 if a == b && a.scale > b.scale 0 if a == b && a.scale == b.scale +1 if a == b && a.scale < b.scale +1 if a > b
CmpTotal panics if amounts are denominated in different currencies. To avoid this panic, use Amount.SameCurr to verify that both amounts have the same currency before calling CmpTotal. See also method Amount.Cmp.
func (Amount) Coef ¶
Coef returns the coefficient of the amount. See also methods Amount.Prec and Amount.MinorUnits.
func (Amount) CopySign ¶
CopySign returns the amount with the same sign as amount b. If amount b is zero, the sign of the result remains unchanged.
func (Amount) FMA ¶
FMA returns the (possibly rounded) fused multiply-addition of amounts a, b, and factor e. It computes a * e + b without any intermeddiate rounding. This method is useful for improving the accuracy and performance of algorithms that involve the accumulation of products, such as daily interest accrual.
FMA panics if:
- amounts are denominated in different currencies. To avoid this panic, use Amount.SameCurr to verify that both amounts have the same currency before calling FMA.
- the integer part of the result exceeds the maximum precision allowed by the currency. This limit is calculated as (decimal.MaxPrec - a.Curr().Scale()). For example, when dealing with US Dollars, FMA will panic if the integer part of the result has more than 17 digits (19 - 2 = 17).
func (Amount) Float64 ¶ added in v0.0.2
Float64 returns a float64 representation of the amount. This conversion may lose data, as float64 has a limited precision compared to the decimal type.
func (Amount) Floor ¶
Floor returns an amount rounded down to the specified number of digits after the decimal point. If the scale of the amount is less than the specified scale, the result will be zero-padded to the right. If the specified scale is less than the scale of the currency, the amount will be rounded down to the scale of the currency instead. See also method Amount.FloorToCurr.
Floor panics if the integer part of the result exceeds the maximum precision, calculated as (decimal.MaxPrec - scale).
func (Amount) FloorToCurr ¶
FloorToCurr returns an amount rounded down to the scale of its currency. See also method Amount.SameScaleAsCurr.
func (Amount) Format ¶
Format implements the fmt.Formatter interface. The following format verbs are available:
%s, %v: USD -123.456 %q: "USD -123.456" %f: -123.46 %d: -12346 %c: USD
The '-' format flag can be used with all verbs. The '+', ' ', '0' format flags can be used with all verbs except %c.
Precision is only supported for the %f verb. The default precision is equal to the scale of the currency.
func (Amount) Int64 ¶ added in v0.0.2
Int64 returns a pair of int64 values, where the first represents the integer part and the second represents the fractional part of the amount, such that a = i + f / 10^scale. If the result cannot be accurately represented as a pair of int64 values, the method returns false.
func (Amount) Max ¶
Max returns the larger amount. See also method Amount.CmpTotal.
Max panics if amounts are denominated in different currencies. To avoid this panic, use Amount.SameCurr to verify that both amounts have the same currency before calling Max.
func (Amount) Min ¶
Min returns the smaller amount. See also method Amount.CmpTotal.
Min panics if amounts are denominated in different currencies. To avoid this panic, use Amount.SameCurr to verify that both amounts have the same currency before calling Min.
func (Amount) MinorUnits ¶
MinorUnits returns the (potentially rounded) amount in minor units of currency. If the result cannot be represented as an int64, then false is returned. See also method Amount.RoundToCurr.
func (Amount) Mul ¶
Mul returns the (possibly rounded) product of amount a and factor e.
Mul panics if the integer part of the result exceeds the maximum precision allowed by the currency. This limit is calculated as (decimal.MaxPrec - a.Curr().Scale()). For example, when dealing with US Dollars, Mul will panic if the integer part of the result has more than 17 digits (19 - 2 = 17).
func (Amount) One ¶
One returns an amount with a value of 1, having the same currency and scale as amount a. See also method Amount.ULP.
func (Amount) Prec ¶
Prec returns the number of digits in the coefficient. See also method Amount.Coef.
func (Amount) Quantize ¶
Quantize returns an amount rounded to the same scale as amount b. The sign and value of amount b are ignored. See also method Amount.Round.
Quantize panics if:
- amounts are denominated in different currencies. To avoid this panic, use Amount.SameCurr to verify that both amounts have the same currency before calling Quantize.
- the integer part of the result exceeds the maximum precision, calculated as (decimal.MaxPrec - b.Scale()).
func (Amount) Quo ¶
Quo returns the (possibly rounded) quotient of amount a and divisor e.
Quo panics if:
- divisor is zero. To avoid this panic, use decimal.Decimal.IsZero to verify that decimal is not zero before calling Quo.
- the integer part of the result exceeds the maximum precision allowed by the currency. This limit is calculated as (decimal.MaxPrec - a.Curr().Scale()). For example, when dealing with US Dollars, Quo will panic if the integer part of the result has more than 17 digits (19 - 2 = 17).
func (Amount) Rat ¶
Rat returns the (possibly rounded) ratio between amounts a and b. This method is particularly useful for calculating exchange rates between two currencies or determining percentages within a single currency.
Rat panics if:
- amount is zero. To avoid this panic, use Amount.IsZero to verify that the amount is not zero before calling Rat.
- the integer part of the result exceeds the maximum precision. This limit is set to decimal.MaxPrec digits.
func (Amount) Reduce ¶
Reduce returns the amount with trailing zeros removed up to its currency scale.
func (Amount) Round ¶
Round returns an amount rounded to the specified number of digits after the decimal point. If the scale of the amount is less than the specified scale, the result will be zero-padded to the right. If the specified scale is less than the scale of the currency, the amount will be rounded to the currency's scale instead. See also method Amount.RoundToCurr.
Round panics if the integer part of the result exceeds the maximum precision, calculated as (decimal.MaxPrec - scale).
func (Amount) RoundToCurr ¶
RoundToCurr returns an amount rounded to the scale of its currency. See also method Amount.SameScaleAsCurr.
func (Amount) SameCurr ¶
SameCurr returns true if amounts are denominated in the same currency. See also method Amount.Curr.
func (Amount) SameScale ¶
SameScale returns true if amounts have the same scale. See also method Amount.Scale.
func (Amount) SameScaleAsCurr ¶
SameScaleAsCurr returns true if the scale of the amount matches the scale of its currency. See also method Amount.RoundToCurr.
func (Amount) Split ¶
Split returns a slice of amounts that sum up to the original amount, ensuring the parts are as equal as possible. If the original amount cannot be divided equally among the specified number of parts, the remainder is distributed among the first parts of the slice.
Split panics if the number of parts is not a positive integer.
Example ¶
Output: [USD 0.17 USD 0.17 USD 0.17 USD 0.17 USD 0.17 USD 0.16] [USD 0.21 USD 0.20 USD 0.20 USD 0.20 USD 0.20] [USD 0.26 USD 0.25 USD 0.25 USD 0.25] [USD 0.34 USD 0.34 USD 0.33] [USD 0.51 USD 0.50] [USD 1.01]
func (Amount) String ¶
String implements the fmt.Stringer interface and returns a string representation of an amount. See also methods Currency.String and Decimal.String.
func (Amount) Sub ¶
Sub returns the (possibly rounded) difference of amounts a and b.
Sub panics if:
- amounts are denominated in different currencies. To avoid this panic, use Amount.SameCurr to verify that both amounts have the same currency before calling Sub.
- the integer part of the result exceeds the maximum precision allowed by the currency. This limit is calculated as (decimal.MaxPrec - a.Curr().Scale()). For example, when dealing with Euros, Sub will panic if the integer part of the result has more than 17 digits (19 - 2 = 17).
func (Amount) Trunc ¶
Trunc returns an amount truncated to the specified number of digits after the decimal point. If the scale of the amount is less than the specified scale, the result will be zero-padded to the right. If the specified scale is less than the scale of the currency, the amount will be truncated to the scale of the currency instead. See also method Amount.TruncToCurr.
Trunc panics if the integer part of the result exceeds the maximum precision, calculated as (decimal.MaxPrec - scale).
func (Amount) TruncToCurr ¶
TruncToCurr returns an amount truncated to the scale of its currency. See also method Amount.SameScaleAsCurr.
func (Amount) ULP ¶
ULP (Unit in the Last Place) returns the smallest representable positive difference between two amounts with the same scale as amount a. It can be useful for implementing rounding and comparison algorithms. See also method Amount.One.
type Currency ¶
type Currency uint8
Currency type represents a currency in the global financial system. The zero value is "XXX", which indicates an unknown currency.
Currency is implemented as an integer index into an in-memory array that stores information such as code and scale. This design ensures safe concurrency for multiple goroutines accessing the same Currency value.
When persisting a currency value, use the alphabetic code returned by the Currency.Code method, rather than the integer index, as mapping between index and a particular currency may change in future versions.
const ( XXX Currency = 0 // No Currency XTS Currency = 1 // Test Currency AED Currency = 2 // U.A.E. Dirham AFN Currency = 3 // Afghani ALL Currency = 4 // Lek AMD Currency = 5 // Armenian Dram ANG Currency = 6 // Netherlands Antillian Guilder AOA Currency = 7 // Kwanza ARS Currency = 8 // Argentine Peso AUD Currency = 9 // Australian Dollar AWG Currency = 10 // Aruban Guilder AZN Currency = 11 // Azerbaijan Manat BAM Currency = 12 // Convertible Mark BBD Currency = 13 // Barbados Dollar BDT Currency = 14 // Taka BGN Currency = 15 // Bulgarian Lev BHD Currency = 16 // Bahraini Dinar BIF Currency = 17 // Burundi Franc BMD Currency = 18 // Bermudian Dollar BND Currency = 19 // Brunei Dollar BOB Currency = 20 // Boliviano BRL Currency = 21 // Brazilian Real BSD Currency = 22 // Bahamian Dollar BTN Currency = 23 // Bhutan Ngultrum BWP Currency = 24 // Pula BYN Currency = 25 // Belarussian Ruble BZD Currency = 26 // Belize Dollar CAD Currency = 27 // Canadian Dollar CDF Currency = 28 // Franc Congolais CHF Currency = 29 // Swiss Franc CLP Currency = 30 // Chilean Peso CNY Currency = 31 // Yuan Renminbi COP Currency = 32 // Colombian Peso CRC Currency = 33 // Costa Rican Colon CUP Currency = 34 // Cuban Peso CVE Currency = 35 // Cape Verde Escudo CZK Currency = 36 // Czech Koruna DJF Currency = 37 // Djibouti Franc DKK Currency = 38 // Danish Krone DOP Currency = 39 // Dominican Peso DZD Currency = 40 // Algerian Dinar EGP Currency = 41 // Egyptian Pound ERN Currency = 42 // Eritean Nakfa ETB Currency = 43 // Ethiopian Birr EUR Currency = 44 // Euro FJD Currency = 45 // Fiji Dollar FKP Currency = 46 // Falkland Islands Pound GBP Currency = 47 // Pound Sterling GEL Currency = 48 // Lari GHS Currency = 49 // Cedi GIP Currency = 50 // Gibraltar Pound GMD Currency = 51 // Dalasi GNF Currency = 52 // Guinea Franc GTQ Currency = 53 // Quetzal GWP Currency = 54 // Guinea-Bissau Peso GYD Currency = 55 // Guyana Dollar HKD Currency = 56 // Hong Kong Dollar HNL Currency = 57 // Lempira HRK Currency = 58 // Croatian Kuna HTG Currency = 59 // Gourde HUF Currency = 60 // Forint IDR Currency = 61 // Rupiah ILS Currency = 62 // Israeli Shequel INR Currency = 63 // Indian Rupee IQD Currency = 64 // Iraqi Dinar IRR Currency = 65 // Iranian Rial ISK Currency = 66 // Iceland Krona JMD Currency = 67 // Jamaican Dollar JOD Currency = 68 // Jordanian Dinar JPY Currency = 69 // Yen KES Currency = 70 // Kenyan Shilling KGS Currency = 71 // Som KHR Currency = 72 // Riel KMF Currency = 73 // Comoro Franc KPW Currency = 74 // North Korean Won KRW Currency = 75 // Won KWD Currency = 76 // Kuwaiti Dinar KYD Currency = 77 // Cayman Islands Dollar KZT Currency = 78 // Tenge LAK Currency = 79 // Kip LBP Currency = 80 // Lebanese Pound LKR Currency = 81 // Sri Lanka Rupee LRD Currency = 82 // Liberian Dollar LSL Currency = 83 // Lesotho Loti LYD Currency = 84 // Libyan Dinar MAD Currency = 85 // Moroccan Dirham MDL Currency = 86 // Moldovan Leu MGA Currency = 87 // Malagasy Ariary MKD Currency = 88 // Denar MMK Currency = 89 // Kyat MNT Currency = 90 // Tugrik MOP Currency = 91 // Pataca MRU Currency = 92 // Ouguiya MUR Currency = 93 // Mauritius Rupee MVR Currency = 94 // Rufiyaa MWK Currency = 95 // Malawi Kwacha MXN Currency = 96 // Mexican Peso MYR Currency = 97 // Malaysian Ringgit MZN Currency = 98 // Mozambique Metical NAD Currency = 99 // Namibia Dollar NGN Currency = 100 // Naira NIO Currency = 101 // Cordoba Oro NOK Currency = 102 // Norwegian Krone NPR Currency = 103 // Nepalese Rupee NZD Currency = 104 // New Zealand Dollar OMR Currency = 105 // Rial Omani PAB Currency = 106 // Balboa PEN Currency = 107 // Sol PGK Currency = 108 // Kina PHP Currency = 109 // Philippine Peso PKR Currency = 110 // Pakistan Rupee PLN Currency = 111 // Zloty PYG Currency = 112 // Guarani QAR Currency = 113 // Qatari Rial RON Currency = 114 // Leu RSD Currency = 115 // Serbian Dinar RUB Currency = 116 // Russian Ruble RWF Currency = 117 // Rwanda Franc SAR Currency = 118 // Saudi Riyal SBD Currency = 119 // Solomon Islands Dollar SCR Currency = 120 // Seychelles Rupee SDG Currency = 121 // Sudanese Pound SEK Currency = 122 // Swedish Krona SGD Currency = 123 // Singapore Dollar SHP Currency = 124 // St. Helena Pound SLL Currency = 125 // Leone SOS Currency = 126 // Somali Shilling SRD Currency = 127 // Surinam Dollar SSP Currency = 128 // South Sudanese Pound STN Currency = 129 // Dobra SYP Currency = 130 // Syrian Pound SZL Currency = 131 // Lilangeni THB Currency = 132 // Baht TJS Currency = 133 // Somoni TMT Currency = 134 // Manat TND Currency = 135 // Tunisian Dinar TOP Currency = 136 // Pa'anga TRY Currency = 137 // Turkish Lira TTD Currency = 138 // Trinidad and Tobago Dollar TWD Currency = 139 // New Taiwan Dollar TZS Currency = 140 // Tanzanian Shilling UAH Currency = 141 // Ukrainian Hryvnia UGX Currency = 142 // Uganda Shilling USD Currency = 143 // U.S. Dollar UYU Currency = 144 // Peso Uruguayo UZS Currency = 145 // Uzbekistan Sum VES Currency = 146 // Sovereign Bolivar VND Currency = 147 // Dong VUV Currency = 148 // Vatu WST Currency = 149 // Tala XAF Currency = 150 // CFA Franc BEAC XCD Currency = 151 // East Caribbean Dollar XOF Currency = 152 // CFA Franc BCEAO XPF Currency = 153 // CFP Franc YER Currency = 154 // Yemeni Rial ZAR Currency = 155 // Rand ZMW Currency = 156 // Zambian Kwacha ZWL Currency = 157 // Zimbabwe Dollar )
func MustParseCurr ¶
MustParseCurr is like ParseCurr but panics if the string cannot be parsed. It simplifies safe initialization of global variables holding currencies.
func ParseCurr ¶
ParseCurr converts a string to currency. The input string must be in one of the following formats:
USD usd 840
ParseCurr returns an error if the string does not represent a valid currency code.
func (Currency) Code ¶
Code returns the 3-letter code assigned to the currency by the ISO 4217 standard. This code is a unique identifier of the currency and is used in international finance and commerce. This method always returns a valid code.
func (Currency) Format ¶
Format implements fmt.Formatter interface. The following verbs are available:
%s, %v: USD %q: "USD" %c: USD
The '-' format flag can be used with all verbs.
func (Currency) MarshalText ¶
MarshalText implements encoding.TextMarshaler interface. Also see method Currency.String.
func (Currency) Num ¶
Num returns the 3-digit code assigned to the currency by the ISO 4217 standard. If the currency does not have such a code, the method will return an empty string.
func (Currency) Scale ¶
Scale returns the number of digits after the decimal point required for the minor unit of the currency. This represents the ratio of the minor unit to the major unit. A scale of 0 means that there is no minor unit for the currency, whereas scales of 1, 2, and 3 signify ratios of 10:1, 100:1, and 1000:1, respectively.
func (Currency) String ¶
String method implements the fmt.Stringer interface and returns a string representation of the Currency value.
func (*Currency) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler interface. Also see method ParseCurr.
type ExchangeRate ¶
type ExchangeRate struct {
// contains filtered or unexported fields
}
ExchangeRate represents a unidirectional exchange rate between two currencies. The zero value corresponds to an exchange rate of "XXX/XXX 0", where XXX indicates an unknown currency. This type is designed to be safe for concurrent use by multiple goroutines.
func MustParseExchRate ¶
func MustParseExchRate(base, quote, rate string) ExchangeRate
MustParseExchRate is like ParseExchRate but panics if any of the strings cannot be parsed. It simplifies safe initialization of global variables holding exchange rates.
func NewExchRate ¶
func NewExchRate(base, quote Currency, rate decimal.Decimal) (ExchangeRate, error)
NewExchRate returns a new exchange rate between the base and quote currencies.
func ParseExchRate ¶
func ParseExchRate(base, quote, rate string) (ExchangeRate, error)
ParseExchRate converts currency and decimal strings to a (possibly rounded) exchange rate. See also methods ParseCurr and decimal.Parse.
func (ExchangeRate) Base ¶
func (r ExchangeRate) Base() Currency
Base returns the currency being exchanged.
func (ExchangeRate) CanConv ¶
func (r ExchangeRate) CanConv(b Amount) bool
CanConv returns true if ExchangeRate.Conv can be used to convert the given amount.
func (ExchangeRate) Conv ¶
func (r ExchangeRate) Conv(b Amount) Amount
Conv returns the amount converted from the base currency to the quote currency.
Conv panics if the base currency of the exchange rate does not match the currency of the given amount. To avoid this panic, use the ExchangeRate.CanConv method to ensure the currencies are compatible before calling Conv.
func (ExchangeRate) Format ¶
func (r ExchangeRate) Format(state fmt.State, verb rune)
Format implements fmt.Formatter interface. The following format verbs are available:
%s, %v: USD/EUR 1.2345 %q: "USD/EUR 1.2345" %f: 1.2345 %c: USD/EUR
The '-' format flag can be used with all verbs. The '0' format flags can be used with all verbs except %c.
Precision is only supported for the %f verb. The default precision is equal to the sum of the scales of its base and quote currencies.
func (ExchangeRate) Inv ¶
func (r ExchangeRate) Inv() ExchangeRate
Inv returns the inverse of the exchange rate.
func (ExchangeRate) IsOne ¶
func (r ExchangeRate) IsOne() bool
IsOne returns:
true if r == 1 false otherwise
func (ExchangeRate) IsZero ¶
func (r ExchangeRate) IsZero() bool
IsZero returns:
true if r == 0 false otherwise
func (ExchangeRate) Mul ¶
func (r ExchangeRate) Mul(e decimal.Decimal) ExchangeRate
Mul returns an exchange rate with the same base and quote currencies, but with the rate multiplied by a positive factor e.
Mul panics if factor e is not positive. To avoid this panic, use the decimal.Decimal.IsPos to verify that decimal is positive before calling Mul.
func (ExchangeRate) Prec ¶
func (r ExchangeRate) Prec() int
Prec returns the number of digits in the coefficient.
func (ExchangeRate) Quote ¶
func (r ExchangeRate) Quote() Currency
Quote returns the currency being obtained in exchange for the base currency.
func (ExchangeRate) Round ¶
func (r ExchangeRate) Round(scale int) ExchangeRate
Round returns an exchange rate that is rounded to the specified number of digits after the decimal point. If the scale of the exchange rate is less than the specified scale, the result will be zero-padded to the right. If the specified scale is less than the sum of the scales of the base and quote currency then the exchange rate will be rounded to the sum of scales instead. See also method ExchangeRate.RoundToCurr.
Round panics if the integer part of the result exceeds the maximum precision. This limit is calculated as (decimal.MaxPrec - scale).
Example ¶
Output: EUR/USD 1.23456700 EUR/USD 1.2345670 EUR/USD 1.234567 EUR/USD 1.23457 EUR/USD 1.2346 EUR/USD 1.2346 EUR/USD 1.2346 EUR/USD 1.2346 EUR/USD 1.2346
func (ExchangeRate) RoundToCurr ¶
func (r ExchangeRate) RoundToCurr() ExchangeRate
RoundToCurr returns an exchange rate that is rounded to the sum of the scales of its base and quote currencies. See also method ExchangeRate.SameScaleAsCurr.
func (ExchangeRate) SameCurr ¶
func (r ExchangeRate) SameCurr(q ExchangeRate) bool
SameCurr returns true if exchange rates are denominated in the same base and quote currencies. See also methods ExchangeRate.Base and ExchangeRate.Quote.
func (ExchangeRate) SameScale ¶
func (r ExchangeRate) SameScale(q ExchangeRate) bool
SameScale returns true if exchange rates have the same scale. See also method ExchangeRate.Scale.
func (ExchangeRate) SameScaleAsCurr ¶
func (r ExchangeRate) SameScaleAsCurr() bool
SameScaleAsCurr returns true if the scale of the exchange rate is equal to the sum of the scales of its base and quote currencies. See also method ExchangeRate.RoundToCurr.
func (ExchangeRate) Scale ¶
func (r ExchangeRate) Scale() int
Scale returns the number of digits after the decimal point.
func (ExchangeRate) String ¶
func (r ExchangeRate) String() string
String method implements the fmt.Stringer interface and returns a string representation of the exchange rate. See also methods Currency.String and Decimal.String.
func (ExchangeRate) WithinOne ¶
func (r ExchangeRate) WithinOne() bool
WithinOne returns:
true if 0 <= r < 1 false otherwise