money

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 15, 2023 License: MIT Imports: 4 Imported by: 3

README

Money

githubb codecovb goreportb licenseb godocb versionb

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:

  1. Fork the repository and clone it to your local machine.
  2. Make the desired changes to the code.
  3. Write tests for the changes you made.
  4. Ensure that all tests pass by running go test.
  5. Commit the changes and push them to your fork.
  6. Submit a pull request with a clear description of the changes you made.
  7. 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

Examples

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

func MustParseAmount(curr, amount string) Amount

MustParseAmount is like ParseAmount but panics if any of the strings cannot be parsed. This function simplifies safe initialization of global variables holding amounts.

Example
Output:

USD -1.230

func NewAmount

func NewAmount(curr Currency, amount decimal.Decimal) (Amount, error)

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
Output:

USD 100.00
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

func ParseAmount(curr, amount string) (Amount, error)

ParseAmount converts currency and decimal strings to (possibly rounded) amount. See also methods ParseCurr and decimal.Parse.

Example
Output:

USD -12.34

func (Amount) Abs

func (a Amount) Abs() Amount

Abs returns the absolute value of the amount.

Example
Output:

USD 15.67

func (Amount) Add

func (a Amount) Add(b Amount) Amount

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).
Example
Output:

USD 23.60

func (Amount) Ceil

func (a Amount) Ceil(scale int) Amount

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).

Example
Output:

USD 15.679000
USD 15.67900
USD 15.6790
USD 15.679
USD 15.68
USD 15.68
USD 15.68

func (Amount) CeilToCurr

func (a Amount) CeilToCurr() Amount

CeilToCurr returns an amount rounded up to the scale of its currency. See also method Amount.SameScaleAsCurr.

Example
Output:

JPY 2
USD 1.57
OMR 1.568

func (Amount) Cmp

func (a Amount) Cmp(b Amount) int

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.

Example
Output:

1
0
-1

func (Amount) CmpTotal

func (a Amount) CmpTotal(b Amount) int

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.

Example
Output:

1
0
-1

func (Amount) Coef

func (a Amount) Coef() uint64

Coef returns the coefficient of the amount. See also methods Amount.Prec and Amount.MinorUnits.

Example
Output:

123
57
4

func (Amount) CopySign

func (a Amount) CopySign(b Amount) Amount

CopySign returns the amount with the same sign as amount b. If amount b is zero, the sign of the result remains unchanged.

Example
Output:

USD -23.00
USD 15.67

func (Amount) Curr

func (a Amount) Curr() Currency

Curr returns the currency of the amount.

Example
Output:

USD

func (Amount) FMA

func (a Amount) FMA(e decimal.Decimal, b Amount) Amount

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).
Example
Output:

USD 10.00

func (Amount) Float64 added in v0.0.2

func (a Amount) Float64() (f float64, ok bool)

Float64 returns a float64 representation of the amount. This conversion may lose data, as float64 has a limited precision compared to the decimal type.

Example
Output:

100 true
15.6 true
2.389 true

func (Amount) Floor

func (a Amount) Floor(scale int) Amount

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).

Example
Output:

USD 15.679000
USD 15.67900
USD 15.6790
USD 15.679
USD 15.67
USD 15.67
USD 15.67

func (Amount) FloorToCurr

func (a Amount) FloorToCurr() Amount

FloorToCurr returns an amount rounded down to the scale of its currency. See also method Amount.SameScaleAsCurr.

Example
Output:

JPY 1
USD 1.56
OMR 1.567

func (Amount) Format

func (a Amount) Format(state fmt.State, verb rune)

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.

Example
Output:

USD -123.456
-123.46
-12346
USD

func (Amount) Int64 added in v0.0.2

func (a Amount) Int64() (i int64, f int64, ok bool)

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.

Example
Output:

100 0 true
15 60 true
2 389 true

func (Amount) IsInt

func (a Amount) IsInt() bool

IsInt returns true if the fractional part of the amount is equal to zero.

Example
Output:

true
false

func (Amount) IsNeg

func (a Amount) IsNeg() bool

IsNeg returns:

true  if a < 0
false otherwise
Example
Output:

true
false
false

func (Amount) IsOne

func (a Amount) IsOne() bool

IsOne returns:

true  if a == -1 || a == 1
false otherwise
Example
Output:

true
false

func (Amount) IsPos

func (a Amount) IsPos() bool

IsPos returns:

true  if a > 0
false otherwise
Example
Output:

false
true
false

func (Amount) IsZero

func (a Amount) IsZero() bool

IsZero returns:

true  if a == 0
false otherwise
Example
Output:

false
false
true

func (Amount) Max

func (a Amount) Max(b Amount) Amount

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.

Example
Output:

USD 23.00

func (Amount) Min

func (a Amount) Min(b Amount) Amount

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.

Example
Output:

USD -15.67

func (Amount) MinorUnits

func (a Amount) MinorUnits() (m int64, ok bool)

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.

Example
Output:

-2 true
-168 true
-1679 true

func (Amount) Mul

func (a Amount) Mul(e decimal.Decimal) Amount

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).

Example
Output:

USD 17.10

func (Amount) Neg

func (a Amount) Neg() Amount

Neg returns the amount with the opposite sign.

Example
Output:

USD -15.67

func (Amount) One

func (a Amount) One() Amount

One returns an amount with a value of 1, having the same currency and scale as amount a. See also method Amount.ULP.

Example
Output:

JPY 1
JPY 1.0
JPY 1.00

func (Amount) Prec

func (a Amount) Prec() int

Prec returns the number of digits in the coefficient. See also method Amount.Coef.

Example
Output:

3
2
1

func (Amount) Quantize

func (a Amount) Quantize(b Amount) Amount

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()).
Example
Output:

JPY 15.68
JPY 15.7
JPY 16

func (Amount) Quo

func (a Amount) Quo(e decimal.Decimal) Amount

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).
Example
Output:

USD -7.835

func (Amount) Rat

func (a Amount) Rat(b Amount) decimal.Decimal

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.
Example
Output:

0.8

func (Amount) Reduce

func (a Amount) Reduce() Amount

Reduce returns the amount with trailing zeros removed up to its currency scale.

Example
Output:

JPY 10
USD 20.00
OMR 30.000

func (Amount) Round

func (a Amount) Round(scale int) Amount

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).

Example
Output:

USD 15.679000
USD 15.67900
USD 15.6790
USD 15.679
USD 15.68
USD 15.68
USD 15.68

func (Amount) RoundToCurr

func (a Amount) RoundToCurr() Amount

RoundToCurr returns an amount rounded to the scale of its currency. See also method Amount.SameScaleAsCurr.

Example
Output:

JPY 2
USD 1.57
OMR 1.568

func (Amount) SameCurr

func (a Amount) SameCurr(b Amount) bool

SameCurr returns true if amounts are denominated in the same currency. See also method Amount.Curr.

Example
Output:

false
true

func (Amount) SameScale

func (a Amount) SameScale(b Amount) bool

SameScale returns true if amounts have the same scale. See also method Amount.Scale.

Example
Output:

false
true

func (Amount) SameScaleAsCurr

func (a Amount) SameScaleAsCurr() bool

SameScaleAsCurr returns true if the scale of the amount matches the scale of its currency. See also method Amount.RoundToCurr.

Example
Output:

true
true
false

func (Amount) Scale

func (a Amount) Scale() int

Scale returns the number of digits after the decimal point.

Example
Output:

4
3

func (Amount) Sign

func (a Amount) Sign() int

Sign returns:

-1 if a < 0
 0 if a == 0
+1 if a > 0
Example
Output:

-1
1
0

func (Amount) Split

func (a Amount) Split(n int) []Amount

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

func (a Amount) String() string

String implements the fmt.Stringer interface and returns a string representation of an amount. See also methods Currency.String and Decimal.String.

Example
Output:

USD -1234567890.123456789

func (Amount) Sub

func (a Amount) Sub(b Amount) Amount

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).
Example
Output:

USD 7.60

func (Amount) Trunc

func (a Amount) Trunc(scale int) Amount

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).

Example
Output:

USD 15.679000
USD 15.67900
USD 15.6790
USD 15.679
USD 15.67
USD 15.67
USD 15.67

func (Amount) TruncToCurr

func (a Amount) TruncToCurr() Amount

TruncToCurr returns an amount truncated to the scale of its currency. See also method Amount.SameScaleAsCurr.

Example
Output:

JPY 1
USD 1.56
OMR 1.567

func (Amount) ULP

func (a Amount) ULP() Amount

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.

Example
Output:

JPY 1
JPY 0.1
JPY 0.01

func (Amount) WithinOne

func (a Amount) WithinOne() bool

WithinOne returns:

true  if -1 < a < 1
false otherwise
Example
Output:

false
true
false

func (Amount) Zero

func (a Amount) Zero() Amount

Zero returns an amount with a value of 0, having the same currency and scale as amount a.

Example
Output:

JPY 0
JPY 0.0
JPY 0.00

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

func MustParseCurr(curr string) Currency

MustParseCurr is like ParseCurr but panics if the string cannot be parsed. It simplifies safe initialization of global variables holding currencies.

Example
Output:

USD

func ParseCurr

func ParseCurr(curr string) (Currency, error)

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.

Example
Output:

USD

func (Currency) Code

func (c Currency) Code() string

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.

Example
Output:

JPY
USD
OMR

func (Currency) Format

func (c Currency) Format(state fmt.State, verb rune)

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.

Example
Output:

USD

func (Currency) MarshalText

func (c Currency) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler interface. Also see method Currency.String.

Example
Output:

USD

func (Currency) Num

func (c Currency) Num() string

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.

Example
Output:

392
840
512

func (Currency) Scale

func (c Currency) Scale() int

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.

Example
Output:

0
2
3

func (Currency) String

func (c Currency) String() string

String method implements the fmt.Stringer interface and returns a string representation of the Currency value.

Example
Output:

USD

func (*Currency) UnmarshalText

func (c *Currency) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler interface. Also see method ParseCurr.

Example
Output:

USD

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.

Example
Output:

OMR/USD 0.38497

func NewExchRate

func NewExchRate(base, quote Currency, rate decimal.Decimal) (ExchangeRate, error)

NewExchRate returns a new exchange rate between the base and quote currencies.

Example
Output:

USD/EUR 1.2000

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.

Example
Output:

USD/EUR 1.2000

func (ExchangeRate) Base

func (r ExchangeRate) Base() Currency

Base returns the currency being exchanged.

Example
Output:

USD

func (ExchangeRate) CanConv

func (r ExchangeRate) CanConv(b Amount) bool

CanConv returns true if ExchangeRate.Conv can be used to convert the given amount.

Example
Output:

true
false
false

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.

Example
Output:

JPY 26654.0000

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.

Example
Output:

USD/EUR 1.23456
1.2346
USD/EUR

func (ExchangeRate) Inv

func (r ExchangeRate) Inv() ExchangeRate

Inv returns the inverse of the exchange rate.

Example
Output:

USD/EUR 0.8000

func (ExchangeRate) IsOne

func (r ExchangeRate) IsOne() bool

IsOne returns:

true  if r == 1
false otherwise
Example
Output:

true
false

func (ExchangeRate) IsZero

func (r ExchangeRate) IsZero() bool

IsZero returns:

true  if r == 0
false otherwise
Example
Output:

true
false

func (ExchangeRate) Mul

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.

Example
Output:

USD/EUR 0.99000

func (ExchangeRate) Prec

func (r ExchangeRate) Prec() int

Prec returns the number of digits in the coefficient.

Example
Output:

4
5

func (ExchangeRate) Quote

func (r ExchangeRate) Quote() Currency

Quote returns the currency being obtained in exchange for the base currency.

Example
Output:

EUR

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.

Example
Output:

USD/JPY 133.86
USD/EUR 0.9155
USD/OMR 0.38501

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.

Example
Output:

true
false

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.

Example
Output:

true
false

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.

Example
Output:

true
false
true

func (ExchangeRate) Scale

func (r ExchangeRate) Scale() int

Scale returns the number of digits after the decimal point.

Example
Output:

4
5

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.

Example
Output:

USD/EUR 1.2345

func (ExchangeRate) WithinOne

func (r ExchangeRate) WithinOne() bool

WithinOne returns:

true  if 0 <= r < 1
false otherwise
Example
Output:

false
true

Directories

Path Synopsis
scripts

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL