From cf8ba04474268301b093ec384810d7baf7d3d794 Mon Sep 17 00:00:00 2001 From: Eugene Apenkin Date: Tue, 12 Dec 2023 18:13:15 +0400 Subject: [PATCH] money: implement new constructors and methods --- .github/workflows/go.yml | 4 +- CHANGELOG.md | 43 + README.md | 113 +- amount.go | 853 ++++++++---- amount_test.go | 1012 ++++++++++++-- currency.go | 52 +- currency_data.go | 2 +- doc_test.go | 1910 +++++++++++++++++++-------- exchange_rate.go | 624 +++++++-- exchange_rate_test.go | 703 ++++++++-- go.mod | 2 +- go.sum | 4 +- scripts/currency/currency_data.tmpl | 2 +- 13 files changed, 4116 insertions(+), 1208 deletions(-) diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index c2b4a5d..e88d0b6 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -9,8 +9,7 @@ jobs: strategy: matrix: go-version: [oldstable, stable] - os: [ubuntu-latest] - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Setup Go @@ -37,4 +36,5 @@ jobs: run: go test -race -shuffle=on -coverprofile="coverage.txt" -covermode=atomic ./... - name: Upload test coverage + if: matrix.go-version == 'stable' uses: codecov/codecov-action@v3 diff --git a/CHANGELOG.md b/CHANGELOG.md index d8d6e1a..15b93d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,48 @@ # Changelog +## [0.2.0] - 2023-12-12 + +### Added + +- Implemented constructors: + - `NewAmountFromInt64`, + - `NewAmountFromFloat64`, + - `NewAmountFromMinorUnits`, + - `NewExchRareFromInt64`, + - `NewExchRareFromFloat64`. +- Implemented methods: + - `Amount.Decimal`, + - `Amount.MinScale`, + - `Amount.CmbAbs`, + - `Amount.SubAbs`, + - `Amount.Clamp`, + - `ExchangeRate.Float64`, + - `ExchangeRate.Int64`, + - `ExchangeRate.Decimal`, + - `ExchangeRate.Ceil`, + - `ExchangeRate.Floor`, + - `ExchangeRate.Trunc`, + - `ExchangeRate.Trim`. + - `ExchangeRate.IsPos`, + - `ExchangeRate.Sign`, +- Implemented `NullCurrency` type. + +### Changed + +- Renamed `NewAmount` contructor to `NewAmountFromDecimal`. +- Renamed `NewExchRate` constructor to `NewExchRateFromDecimal`. +- Changed `ExchangeRate.Round`, now it returns an error. +- Changed `ExchangeRate.Format`, now `%c` returns quore currency, not a currency pair. + +### Removed + +- Removed methods: + - `Amount.Prec`, + - `Amount.Coef`, + - `ExchangeRate.RoundToCurr`, + - `ExchangeRate.Prec`, + - `ExchangeRate.SameScaleAsCurr`. + ## [0.1.3] - 2023-08-21 ### Added diff --git a/README.md b/README.md index e88f3d2..3f09638 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Money +# money [![githubb]][github] [![codecovb]][codecov] @@ -6,73 +6,96 @@ [![godocb]][godoc] [![licenseb]][license] [![versionb]][version] +[![awesomeb]][awesome] 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: +### Installation + +To add the money package to your Go workspace: ```bash go get github.com/govalues/money ``` -To use the money package in your Go project, you can import it as follows: +### Usage + +Create amount using one of the constructors. +After creating a monetary amount, various operations can be performed: ```go +package main + import ( + "fmt" "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`, `MustNewAmount`, `ParseAmount` or `MustParseAmount`. -```go -d := decimal.MustNew(12345, 2) // d = 123.45 -a := money.MustNewAmount(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. - -```go -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) +func main() { + x, _ := decimal.New(2, 0) // x = 2 + + // Constructors + a, _ := money.NewAmount("USD", 8, 0) // a = USD 8.00 + b, _ := money.ParseAmount("USD", "12.5") // b = USD 12.50 + c, _ := money.NewAmountFromFloat64("USD", 2.567) // c = USD 2.567 + d, _ := money.NewAmountFromInt64("USD", 7, 896, 3) // d = USD 7.896 + r, _ := money.NewExchRate("USD", "EUR", 9, 1) // r = USD/EUR 0.9 + + // Operations + fmt.Println(a.Add(b)) // USD 8.00 + USD 12.50 + fmt.Println(a.Sub(b)) // USD 8.00 - USD 12.50 + + fmt.Println(a.Mul(x)) // USD 8.00 * 2 + fmt.Println(a.FMA(x, b)) // USD 8.00 * 2 + USD 12.50 + fmt.Println(r.Conv(a)) // USD/EUR 0.9 * USD 8.00 + + fmt.Println(a.Quo(x)) // USD 8.00 / 2 + fmt.Println(a.QuoRem(x)) // USD 8.00 div 2, USD 8.00 mod 2 + fmt.Println(a.Rat(b)) // USD 8.00 / USD 12.50 + fmt.Println(a.Split(3)) // USD 8.00 into 3 parts + + // Rounding to 2 decimal places + fmt.Println(c.RoundToCurr()) // 2.57 + fmt.Println(c.CeilToCurr()) // 2.57 + fmt.Println(c.FloorToCurr()) // 2.56 + fmt.Println(c.TruncToCurr()) // 2.56 + + // Conversions + fmt.Println(d.Int64(9)) // 7 896000000 + fmt.Println(d.Float64()) // 7.896 + fmt.Println(d.String()) // USD 7.896 + + // Formatting + fmt.Printf("%v\n", d) // USD 7.896 + fmt.Printf("%[1]f %[1]c\n", d) // 7.896 USD + fmt.Printf("%f\n", d) // 7.896 + fmt.Printf("%c\n", d) // USD + fmt.Printf("%d\n", d) // 790 +} ``` -For more details on these and other methods, see the package documentation at [pkg.go.dev](https://pkg.go.dev/github.com/govalues/money). - -## Benchmarks +## Documentation -For the benchmark results please check description of [decimal](https://github.com/govalues/decimal) package. +For detailed documentation and additional examples, visit the package +[documentation](https://pkg.go.dev/github.com/govalues/money#pkg-examples). -## Contributing to the project +## Contributing -The money package is hosted on [GitHub](https://github.com/govalues/money). -To contribute to the project, follow these steps: +Interested in contributing? Here's how to get started: - 1. Fork the repository and clone it to your local machine. - 1. Make the desired changes to the code. - 1. Write tests for the changes you made. - 1. Ensure that all tests pass by running `go test`. - 1. Commit the changes and push them to your fork. - 1. Submit a pull request with a clear description of the changes you made. - 1. Wait for the maintainers to review and merge your changes. +1. Fork and clone the repository. +1. Implement your changes. +1. Write tests to cover your changes. +1. Ensure all tests pass with `go test`. +1. Commit and push to your fork. +1. Open a pull request detailing 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. +**Note**: If you're considering significant changes, please open an issue first to +discuss with the maintainers. +This ensures alignment with the project's objectives and roadmap. [codecov]: https://codecov.io/gh/govalues/money [codecovb]: https://img.shields.io/codecov/c/github/govalues/money/main?color=brightcolor @@ -86,3 +109,5 @@ Note: Before making any significant changes to the code, it is recommended to op [versionb]: https://img.shields.io/github/go-mod/go-version/govalues/money?label=go [license]: https://en.wikipedia.org/wiki/MIT_License [licenseb]: https://img.shields.io/github/license/govalues/money?color=blue +[awesome]: https://github.com/avelino/awesome-go#financial +[awesomeb]: https://awesome.re/mentioned-badge.svg diff --git a/amount.go b/amount.go index 509ffed..9f7dae5 100644 --- a/amount.go +++ b/amount.go @@ -4,6 +4,8 @@ import ( "errors" "fmt" "math" + "strconv" + "strings" "github.com/govalues/decimal" ) @@ -11,56 +13,195 @@ import ( var errCurrencyMismatch = errors.New("currency mismatch") // 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. +// Its zero value corresponds to "XXX 0", where XXX indicates an unknown currency. +// Amount is designed to be safe for concurrent use by multiple goroutines. type Amount struct { - curr Currency // an ISO 4217 currency code - value decimal.Decimal // the monetary value + curr Currency // ISO 4217 currency + value decimal.Decimal // monetary value } -func newAmountUnsafe(curr Currency, amount decimal.Decimal) Amount { - return Amount{curr: curr, value: amount} +// newAmountUnsafe creates a new amount without checking the scale. +// Use it only if you are absolutely sure that the arguments are valid. +func newAmountUnsafe(c Currency, d decimal.Decimal) Amount { + return Amount{curr: c, value: d} } -// NewAmount returns a new amount with the specified currency and value. +// newAmountSafe creates a new amount and checks the scale. +func newAmountSafe(c Currency, d decimal.Decimal) (Amount, error) { + if d.Scale() < c.Scale() { + var err error + d, err = d.Pad(c.Scale()) + if err != nil { + return Amount{}, fmt.Errorf("padding amount: %w", err) + } + } + return newAmountUnsafe(c, d), nil +} + +// NewAmount returns an amount equal to coef / 10^scale. // If the scale of the amount is less than the scale of the currency, the result // will be zero-padded to the right. -func NewAmount(curr Currency, amount decimal.Decimal) (Amount, error) { - amount, err := amount.Pad(curr.Scale()) +// +// NewAmount returns an error if: +// - the currency code is not valid; +// - the scale is negative or greater than [decimal.MaxScale]; +// - the integer part of the result has more than +// ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when currency is US Dollars, NewAmount will return an error +// if the integer part of the result has more than 17 digits (19 - 2 = 17). +func NewAmount(curr string, coef int64, scale int) (Amount, error) { + // Currency + c, err := ParseCurr(curr) + if err != nil { + return Amount{}, fmt.Errorf("parsing currency: %w", err) + } + // Decimal + d, err := decimal.New(coef, scale) + if err != nil { + return Amount{}, fmt.Errorf("converting coefficient: %w", err) + } + // Amount + a, err := newAmountSafe(c, d) if err != nil { - return Amount{}, fmt.Errorf("padding: %w", err) + return Amount{}, fmt.Errorf("converting coefficient: %w", err) } - return newAmountUnsafe(curr, amount), nil + return a, nil } -// MustNewAmount is like [NewAmount] but panics if the amount cannot be created. -// This function simplifies safe initialization of global variables holding amounts. -func MustNewAmount(curr Currency, amount decimal.Decimal) Amount { - a, err := NewAmount(curr, amount) +// MustNewAmount is like [NewAmount] but panics if the amount cannot be constructed. +// It simplifies safe initialization of global variables holding amounts. +func MustNewAmount(curr string, coef int64, scale int) Amount { + a, err := NewAmount(curr, coef, scale) if err != nil { - panic(fmt.Sprintf("NewAmount(%v, %v) failed: %v", curr, amount, err)) + panic(fmt.Sprintf("NewAmount(%q, %v, %v) failed: %v", curr, coef, scale, err)) } return a } -// ParseAmount converts currency and decimal strings to (possibly rounded) amount. +// NewAmountFromDecimal returns an 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. See also method [Amount.Decimal]. +// +// NewAmountFromDecimal returns an error if the integer part of the result has more than +// ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when currency is US Dollars, NewAmountFromDecimal will return an error if +// the integer part of the result has more than 17 digits (19 - 2 = 17). +func NewAmountFromDecimal(curr Currency, amount decimal.Decimal) (Amount, error) { + return newAmountSafe(curr, amount) +} + +// NewAmountFromInt64 converts a pair of integers, representing the whole and +// fractional parts, to a (possibly rounded) amount equal to whole + frac / 10^scale. +// NewAmountFromInt64 deletes trailing zeros up to the scale of the currency. +// This method is useful for converting amounts from [protobuf] format. +// See also method [Amount.Int64]. +// +// NewAmountFromInt64 returns an error if: +// - the currency code is not valid; +// - the whole and fractional parts have different signs; +// - the scale is negative or greater than [decimal.MaxScale]; +// - frac / 10^scale is not within the range (-1, 1); +// - the integer part of the result has more than +// ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when currency is US Dollars, NewAmountFromInt64 will return +// an error if the integer part of the result has more than 17 digits (19 - 2 = 17). +// +// [protobuf]: https://github.com/googleapis/googleapis/blob/master/google/type/money.proto +func NewAmountFromInt64(curr string, whole, frac int64, scale int) (Amount, error) { + // Currency + c, err := ParseCurr(curr) + if err != nil { + return Amount{}, fmt.Errorf("parsing currency: %w", err) + } + // Whole + d, err := decimal.New(whole, 0) + if err != nil { + return Amount{}, fmt.Errorf("converting integers: %w", err) + } + // Fraction + f, err := decimal.New(frac, scale) + if err != nil { + return Amount{}, fmt.Errorf("converting integers: %w", err) + } + if !f.IsZero() { + if !d.IsZero() && d.Sign() != f.Sign() { + return Amount{}, fmt.Errorf("converting integers: inconsistent signs") + } + if !f.WithinOne() { + return Amount{}, fmt.Errorf("converting integers: inconsistent fraction") + } + f = f.Trim(c.Scale()) + d, err = d.AddExact(f, c.Scale()) + if err != nil { + return Amount{}, fmt.Errorf("converting integers: %w", err) + } + } + // Amount + return newAmountSafe(c, d) +} + +// NewAmountFromMinorUnits converts an integer, representing minor units of +// currency (e.g. cents, pennies, fens), to an amount. +// See also method [Amount.MinorUnits]. +// +// NewAmountFromMinorUnits returns an error if currency code is not valid. +func NewAmountFromMinorUnits(curr string, units int64) (Amount, error) { + // Currency + c, err := ParseCurr(curr) + if err != nil { + return Amount{}, fmt.Errorf("parsing currency: %w", err) + } + // Decimal + d, err := decimal.New(units, c.Scale()) + if err != nil { + return Amount{}, fmt.Errorf("converting minor units: %w", err) + } + // Amount + return newAmountSafe(c, d) +} + +// NewAmountFromFloat64 converts a float to a (possibly rounded) amount. +// See also method [Amount.Float64]. +// +// NewAmountFromFloat64 returns an error if: +// - the currency code is not valid; +// - the float is a special value (NaN or Inf); +// - the integer part of the result has more than +// ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when currency is US Dollars, NewAmountFromFloat64 will +// return an error if the integer part of the result has more than 17 +// digits (19 - 2 = 17). +func NewAmountFromFloat64(curr string, amount float64) (Amount, error) { + // Float + if math.IsNaN(amount) || math.IsInf(amount, 0) { + return Amount{}, fmt.Errorf("converting float: special value %v", amount) + } + s := strconv.FormatFloat(amount, 'f', -1, 64) + // Amount + a, err := ParseAmount(curr, s) + if err != nil { + return Amount{}, fmt.Errorf("converting float: %w", err) + } + return a, nil +} + +// ParseAmount converts currency and decimal strings to a (possibly rounded) amount. // If the scale of the amount is less than the scale of the currency, the result // will be zero-padded to the right. -// See also methods [ParseCurr] and [decimal.Parse]. +// See also constructors [ParseCurr] and [decimal.Parse]. func ParseAmount(curr, amount string) (Amount, error) { + // Currency c, err := ParseCurr(curr) if err != nil { return Amount{}, fmt.Errorf("parsing currency: %w", err) } + // Decimal d, err := decimal.ParseExact(amount, c.Scale()) if err != nil { return Amount{}, fmt.Errorf("parsing amount: %w", err) } - a, err := NewAmount(c, d) - if err != nil { - return Amount{}, fmt.Errorf("new amount: %w", err) - } - return a, nil + // Amount + return newAmountSafe(c, d) } // MustParseAmount is like [ParseAmount] but panics if any of the strings cannot be parsed. @@ -73,18 +214,19 @@ func MustParseAmount(curr, amount string) Amount { return a } -// Coef returns the coefficient of the amount. -// See also methods [Amount.Prec] and [Amount.MinorUnits]. -func (a Amount) Coef() uint64 { - return a.value.Coef() -} - -// MinorUnits returns the (potentially rounded) amount in minor units of currency. +// MinorUnits returns a (possibly rounded) amount in minor units of currency +// (e.g. cents, pennies, fens). +// If the scale of the amount is greater than the scale of the currency, then +// the fractional part is rounded using [rounding half to even] (banker's rounding). +// See also constructor [NewAmountFromMinorUnits]. +// // If the result cannot be represented as an int64, then false is returned. -// See also method [Amount.RoundToCurr]. -func (a Amount) MinorUnits() (m int64, ok bool) { - coef := a.RoundToCurr().Coef() - if a.IsNeg() { +// +// [rounding half to even]: https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even +func (a Amount) MinorUnits() (units int64, ok bool) { + d := a.RoundToCurr().Decimal() + coef := d.Coef() + if d.IsNeg() { if coef > -math.MinInt64 { return 0, false } @@ -96,26 +238,40 @@ func (a Amount) MinorUnits() (m int64, ok bool) { return int64(coef), true } -// Float64 returns a float64 representation of the amount. -// This conversion may lose data, as float64 has a limited precision -// compared to the decimal type. +// Float64 returns the nearest binary floating-point number rounded +// using [rounding half to even] (banker's rounding). +// See also constructor [NewAmountFromFloat64]. +// +// This conversion may lose data, as float64 has a smaller precision +// than the decimal type. +// +// [rounding half to even]: https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even func (a Amount) Float64() (f float64, ok bool) { - return a.value.Float64() -} - -// Int64 returns a pair of int64 values representing the integer part b and the -// fractional part f of the amount. -// The relationship can be expressed as a = b + f / 10^scale. -// If the result cannot be accurately represented as a pair of int64 values, -// the method returns false. -func (a Amount) Int64(scale int) (b, f int64, ok bool) { - return a.value.Int64(scale) + return a.Decimal().Float64() } -// Prec returns the number of digits in the coefficient. -// See also method [Amount.Coef]. -func (a Amount) Prec() int { - return a.value.Prec() +// Int64 returns a pair of integers representing the whole and (possibly +// rounded) fractional parts of the amount. +// If given scale is greater than the scale of the amount, then the fractional part +// is zero-padded to the right. +// If given scale is smaller than the scale of the amount, then the fractional part +// is rounded using [rounding half to even] (banker's rounding). +// The relationship between the amount and the returned values can be expressed +// as a = whole + frac / 10^scale. +// This method is useful for converting amounts to [protobuf] format. +// See also constructor [NewAmountFromInt64]. +// +// Int64 returns false if: +// - given scale is smaller than the scale of the currency; +// - the result cannot be represented as a pair of int64 values. +// +// [rounding half to even]: https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even +// [protobuf]: https://github.com/googleapis/googleapis/blob/master/google/type/money.proto +func (a Amount) Int64(scale int) (whole, frac int64, ok bool) { + if scale < a.Curr().Scale() { + return 0, 0, false + } + return a.Decimal().Int64(scale) } // Curr returns the currency of the amount. @@ -123,13 +279,18 @@ func (a Amount) Curr() Currency { return a.curr } +// Decimal returns the decimal representation of the amount. +func (a Amount) Decimal() decimal.Decimal { + return a.value +} + // Sign returns: // // -1 if a < 0 -// 0 if a == 0 +// 0 if a = 0 // +1 if a > 0 func (a Amount) Sign() int { - return a.value.Sign() + return a.Decimal().Sign() } // IsNeg returns: @@ -137,7 +298,7 @@ func (a Amount) Sign() int { // true if a < 0 // false otherwise func (a Amount) IsNeg() bool { - return a.value.IsNeg() + return a.Decimal().IsNeg() } // IsPos returns: @@ -145,52 +306,64 @@ func (a Amount) IsNeg() bool { // true if a > 0 // false otherwise func (a Amount) IsPos() bool { - return a.value.IsPos() + return a.Decimal().IsPos() } // Abs returns the absolute value of the amount. func (a Amount) Abs() Amount { - d := a.value - return newAmountUnsafe(a.Curr(), d.Abs()) + return newAmountUnsafe(a.Curr(), a.Decimal().Abs()) } -// Neg returns the amount with the opposite sign. +// Neg returns an amount with the opposite sign. func (a Amount) Neg() Amount { - d := a.value - return newAmountUnsafe(a.Curr(), d.Neg()) + return newAmountUnsafe(a.Curr(), a.Decimal().Neg()) } -// CopySign returns the amount with the same sign as amount b. -// Zero is always treated as positive. +// CopySign returns an amount with the same sign as amount b. +// The currency of amount b is ignored. +// CopySign treates zero as positive. +// See also method [Amount.Sign]. func (a Amount) CopySign(b Amount) Amount { - d, e := a.value, b.value + d, e := a.Decimal(), b.Decimal() return newAmountUnsafe(a.Curr(), d.CopySign(e)) } // Scale returns the number of digits after the decimal point. +// See also method [Amount.MinScale]. func (a Amount) Scale() int { - return a.value.Scale() + return a.Decimal().Scale() +} + +// MinScale returns the smallest scale that the amount can be rescaled to +// without rounding. +// See also method [Amount.Trim]. +func (a Amount) MinScale() int { + s := a.Decimal().MinScale() + if s < a.Curr().Scale() { + s = a.Curr().Scale() + } + return s } // IsZero returns: // -// true if a == 0 +// true if a = 0 // false otherwise func (a Amount) IsZero() bool { - return a.value.IsZero() + return a.Decimal().IsZero() } // IsOne returns: // -// true if a == -1 || a == 1 +// true if a = -1 or a = 1 // false otherwise func (a Amount) IsOne() bool { - return a.value.IsOne() + return a.Decimal().IsOne() } -// IsInt returns true if the fractional part of the amount is equal to zero. +// IsInt returns true if there are no significant digits after the decimal point. func (a Amount) IsInt() bool { - return a.value.IsInt() + return a.Decimal().IsInt() } // WithinOne returns: @@ -198,117 +371,170 @@ func (a Amount) IsInt() bool { // true if -1 < a < 1 // false otherwise func (a Amount) WithinOne() bool { - return a.value.WithinOne() + return a.Decimal().WithinOne() } // Add returns the (possibly rounded) sum of amounts a and b. // // Add returns an error if: -// - amounts are denominated in different currencies. -// - 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 return an error if the integer +// - amounts are denominated in different currencies; +// - the integer part of the result has more than ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when currency is US Dollars, Add will return an error if the integer // part of the result has more than 17 digits (19 - 2 = 17). func (a Amount) Add(b Amount) (Amount, error) { + c, err := a.add(b) + if err != nil { + return Amount{}, fmt.Errorf("computing [%v + %v]: %w", a, b, err) + } + return c, nil +} + +func (a Amount) add(b Amount) (Amount, error) { if !a.SameCurr(b) { - return Amount{}, fmt.Errorf("%q + %q: %w", a, b, errCurrencyMismatch) + return Amount{}, errCurrencyMismatch } - d, e := a.value, b.value - f, err := d.AddExact(e, a.Curr().Scale()) + c, d, e := a.Curr(), a.Decimal(), b.Decimal() + d, err := d.AddExact(e, c.Scale()) if err != nil { - return Amount{}, fmt.Errorf("%q + %q: %w", a, b, err) + return Amount{}, err } - return NewAmount(a.Curr(), f) + return newAmountSafe(c, d) } -// Sub returns the (possibly rounded) difference of amounts a and b. +// Sub returns the (possibly rounded) difference between amounts a and b. // // Sub returns an error if: -// - amounts are denominated in different currencies. -// - 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, Sub will return an error if the integer +// - amounts are denominated in different currencies; +// - the integer part of the result has more than ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when currency is US Dollars, Sub will return an error if the integer // part of the result has more than 17 digits (19 - 2 = 17). func (a Amount) Sub(b Amount) (Amount, error) { + c, err := a.sub(b) + if err != nil { + return Amount{}, fmt.Errorf("computing [%v - %v]: %w", a, b, err) + } + return c, nil +} + +// SubAbs returns the (possibly rounded) absolute difference between amounts a and b. +// +// SubAbs returns an error if: +// - amounts are denominated in different currencies; +// - the integer part of the result has more than ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when currency is US Dollars, SubAbs will return an error if the integer +// part of the result has more than 17 digits (19 - 2 = 17). +func (a Amount) SubAbs(b Amount) (Amount, error) { + c, err := a.sub(b) + if err != nil { + return Amount{}, fmt.Errorf("computing [abs(%v - %v)]: %w", a, b, err) + } + return c.Abs(), nil +} + +func (a Amount) sub(b Amount) (Amount, error) { if !a.SameCurr(b) { - return Amount{}, fmt.Errorf("%q - %q: %w", a, b, errCurrencyMismatch) + return Amount{}, errCurrencyMismatch } - d, e := a.value, b.value - f, err := d.SubExact(e, a.Curr().Scale()) + c, d, e := a.Curr(), a.Decimal(), b.Decimal() + d, err := d.SubExact(e, c.Scale()) if err != nil { - return Amount{}, fmt.Errorf("%q - %q: %w", a, b, err) + return Amount{}, err } - return NewAmount(a.Curr(), f) + return newAmountSafe(c, d) } // FMA returns the (possibly rounded) [fused multiply-addition] of amounts a, b, and factor e. -// It computes a * e + b without any intermeddiate rounding. +// It computes a * e + b without any intermediate 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 returns an error if: -// - amounts are denominated in different currencies. -// - 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 return an error if the integer +// - amounts are denominated in different currencies; +// - the integer part of the result has more than ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when currency is US Dollars, FMA will return an error if the integer // part of the result has more than 17 digits (19 - 2 = 17). // // [fused multiply-addition]: https://en.wikipedia.org/wiki/Multiply%E2%80%93accumulate_operation#Fused_multiply%E2%80%93add func (a Amount) FMA(e decimal.Decimal, b Amount) (Amount, error) { + c, err := a.fma(e, b) + if err != nil { + return Amount{}, fmt.Errorf("computing [%v * %v + %v]: %w", a, e, b, err) + } + return c, nil +} + +func (a Amount) fma(e decimal.Decimal, b Amount) (Amount, error) { if !a.SameCurr(b) { - return Amount{}, fmt.Errorf("%q * %v + %q: %w", a, e, b, errCurrencyMismatch) + return Amount{}, errCurrencyMismatch } - d, f := a.value, b.value - d, err := d.FMAExact(e, f, a.Curr().Scale()) + c, d, f := a.Curr(), a.Decimal(), b.Decimal() + d, err := d.FMAExact(e, f, c.Scale()) if err != nil { - return Amount{}, fmt.Errorf("%q * %v + %q: %w", a, e, b, err) + return Amount{}, err } - return NewAmount(a.Curr(), d) + return newAmountSafe(c, d) } // Mul returns the (possibly rounded) product of amount a and factor e. // -// Mul returns an error 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 return an error if the integer +// Mul returns an error if the integer part of the result has more than +// ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when currency is US Dollars, Mul will return an error if the integer // part of the result has more than 17 digits (19 - 2 = 17). func (a Amount) Mul(e decimal.Decimal) (Amount, error) { - d := a.value - f, err := d.MulExact(e, a.Curr().Scale()) + c, err := a.mul(e) if err != nil { - return Amount{}, fmt.Errorf("%q * %v: %w", a, e, err) + return Amount{}, fmt.Errorf("computing [%v * %v]: %w", a, e, err) } - return NewAmount(a.Curr(), f) + return c, nil +} + +func (a Amount) mul(e decimal.Decimal) (Amount, error) { + c, d := a.Curr(), a.Decimal() + d, err := d.MulExact(e, c.Scale()) + if err != nil { + return Amount{}, err + } + return newAmountSafe(c, d) } // Quo returns the (possibly rounded) quotient of amount a and divisor e. +// See also methods [Amount.QuoRem], [Amount.Rat], and [Amount.Split]. // // Quo returns an error if: -// - divisor is zero. -// - 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 return an error if the integer +// - the divisor is zero; +// - the integer part of the result has more than ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when currency is US Dollars, Quo will return an error if the integer // part of the result has more than 17 digits (19 - 2 = 17). func (a Amount) Quo(e decimal.Decimal) (Amount, error) { - d := a.value - d, err := d.QuoExact(e, a.Curr().Scale()) + c, err := a.quo(e) + if err != nil { + return Amount{}, fmt.Errorf("computing [%v / %v]: %w", a, e, err) + } + return c, nil +} + +func (a Amount) quo(e decimal.Decimal) (Amount, error) { + c, d := a.Curr(), a.Decimal() + d, err := d.QuoExact(e, c.Scale()) if err != nil { - return Amount{}, fmt.Errorf("%q / %v: %w", a, e, err) + return Amount{}, err } - return NewAmount(a.Curr(), d) + return newAmountSafe(c, d) } -// QuoRem returns the quotient q and remainder r of decimals d and e -// such that d = e * q + r, where q has scale equal to the scale of the currency. +// QuoRem returns the quotient q and remainder r of amount a and divisor e +// such that a = e * q + r, where q has scale equal to the scale of its currency +// and the sign of the reminder r is the same as the sign of the dividend d. +// See also methods [Amount.Quo], [Amount.Rat], and [Amount.Split]. // // QuoRem returns an error if: -// - the integer part of the quotient q has more than [MaxPrec] digits; -// - the divisor e is zero. +// - the divisor is zero; +// - the integer part of the result has more than [decimal.MaxPrec] digits. func (a Amount) QuoRem(e decimal.Decimal) (q, r Amount, err error) { q, r, err = a.quoRem(e) if err != nil { - return Amount{}, Amount{}, fmt.Errorf("[āŒŠ%q / %vāŒ‹ %q mod %v]: %w", a, e, a, e, err) + return Amount{}, Amount{}, fmt.Errorf("computing [%v div %v] and [%v mod %v]: %w", a, e, a, e, err) } return q, r, nil } @@ -319,7 +545,9 @@ func (a Amount) quoRem(e decimal.Decimal) (q, r Amount, err error) { if err != nil { return Amount{}, Amount{}, err } - q = q.Trunc(a.Curr().Scale()) + + // T-Division + q = q.TruncToCurr() // Reminder r, err = q.Mul(e) @@ -336,53 +564,54 @@ func (a Amount) quoRem(e decimal.Decimal) (q, r Amount, err error) { // 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. +// See also methods [Amount.Quo], [Amount.QuoRem], and [Amount.Split]. // // Rat returns an error if: -// - divisor is zero. -// - the integer part of the result exceeds the maximum precision. -// This limit is set to [decimal.MaxPrec] digits. +// - the divisor is zero; +// - the integer part of the result has more than [decimal.MaxPrec] digits. func (a Amount) Rat(b Amount) (decimal.Decimal, error) { - d, e := a.value, b.value - f, err := d.Quo(e) + d, e := a.Decimal(), b.Decimal() + d, err := d.Quo(e) if err != nil { - return decimal.Decimal{}, fmt.Errorf("%q / %q: %w", a, b, err) + return decimal.Decimal{}, fmt.Errorf("computing [%v / %v]: %w", a, b, err) } - return f, nil + return d, nil } // 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. +// 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. +// See also methods [Amount.Quo], [Amount.QuoRem], and [Amount.Rat]. // // Split returns an error if the number of parts is not a positive integer. func (a Amount) Split(parts int) ([]Amount, error) { r, err := a.split(parts) if err != nil { - return nil, fmt.Errorf("splitting %q into %v parts: %w", a, parts, err) + return nil, fmt.Errorf("splitting %v into %v parts: %w", a, parts, err) } return r, nil } func (a Amount) split(parts int) ([]Amount, error) { // Parts - div, err := decimal.New(int64(parts), 0) + par, err := decimal.New(int64(parts), 0) if err != nil { return nil, err } - if !div.IsPos() { + if !par.IsPos() { return nil, fmt.Errorf("number of parts must be positive") } // Quotient - quo, err := a.Quo(div) + quo, err := a.Quo(par) if err != nil { return nil, err } quo = quo.Trunc(a.Scale()) // Reminder - rem, err := quo.Mul(div) + rem, err := quo.Mul(par) if err != nil { return nil, err } @@ -392,10 +621,10 @@ func (a Amount) split(parts int) ([]Amount, error) { } ulp := rem.ULP().CopySign(rem) - // Reminder distribution res := make([]Amount, parts) for i := 0; i < parts; i++ { res[i] = quo + // Reminder distribution if !rem.IsZero() { rem, err = rem.Sub(ulp) if err != nil { @@ -410,151 +639,185 @@ func (a Amount) split(parts int) ([]Amount, error) { return res, nil } -// One returns an amount with a value of 1, having the same currency and scale as amount a. -// See also method [Amount.ULP]. +// One returns an amount with a value of 1, having the same currency and scale +// as amount a. +// See also methods [Amount.Zero], [Amount.ULP]. func (a Amount) One() Amount { - d := a.value - return newAmountUnsafe(a.Curr(), d.One()) + return newAmountUnsafe(a.Curr(), a.Decimal().One()) } -// Zero returns an amount with a value of 0, having the same currency and scale as amount a. +// Zero returns an amount with a value of 0, having the same currency and scale +// as amount a. +// See also methods [Amount.One], [Amount.ULP]. func (a Amount) Zero() Amount { - d := a.value - return newAmountUnsafe(a.Curr(), d.Zero()) + return newAmountUnsafe(a.Curr(), a.Decimal().Zero()) } // 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]. +// See also methods [Amount.Zero], [Amount.One]. func (a Amount) ULP() Amount { - d := a.value - return newAmountUnsafe(a.Curr(), d.ULP()) + return newAmountUnsafe(a.Curr(), a.Decimal().ULP()) } // Ceil returns an amount rounded up to the specified number of digits after -// the decimal point. +// the decimal point using [rounding toward positive infinity]. // If the given scale is less than the scale of the currency, // the amount will be rounded up to the scale of the currency instead. -// See also method [Amount.CeilToCurr]. +// See also methods [Amount.CeilToCurr], [Amount.Floor]. +// +// [rounding toward positive infinity]: https://en.wikipedia.org/wiki/Rounding#Rounding_up func (a Amount) Ceil(scale int) Amount { - if scale < a.Curr().Scale() { - scale = a.Curr().Scale() + c, d := a.Curr(), a.Decimal() + if scale < c.Scale() { + scale = c.Scale() } - d := a.value - return newAmountUnsafe(a.Curr(), d.Ceil(scale)) + d = d.Ceil(scale) + return newAmountUnsafe(c, d) } -// CeilToCurr returns an amount rounded up to the scale of its currency. -// See also method [Amount.SameScaleAsCurr]. +// CeilToCurr returns an amount rounded up to the scale of its currency +// using [rounding toward positive infinity]. +// See also methods [Amount.Ceil], [Amount.SameScaleAsCurr]. +// +// [rounding toward positive infinity]: https://en.wikipedia.org/wiki/Rounding#Rounding_up func (a Amount) CeilToCurr() Amount { return a.Ceil(a.Curr().Scale()) } // Floor returns an amount rounded down to the specified number of digits after -// the decimal point. +// the decimal point using [rounding toward negative infinity]. // If the given 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]. +// See also methods [Amount.FloorToCurr], [Amount.Ceil]. +// +// [rounding toward negative infinity]: https://en.wikipedia.org/wiki/Rounding#Rounding_down func (a Amount) Floor(scale int) Amount { - if scale < a.Curr().Scale() { - scale = a.Curr().Scale() + c, d := a.Curr(), a.Decimal() + if scale < c.Scale() { + scale = c.Scale() } - d := a.value - return newAmountUnsafe(a.Curr(), d.Floor(scale)) + d = d.Floor(scale) + return newAmountUnsafe(c, d) } -// FloorToCurr returns an amount rounded down to the scale of its currency. -// See also method [Amount.SameScaleAsCurr]. +// FloorToCurr returns an amount rounded down to the scale of its currency +// using [rounding toward negative infinity]. +// See also methods [Amount.Floor], [Amount.SameScaleAsCurr]. +// +// [rounding toward negative infinity]: https://en.wikipedia.org/wiki/Rounding#Rounding_down func (a Amount) FloorToCurr() Amount { return a.Floor(a.Curr().Scale()) } // Trunc returns an amount truncated to the specified number of digits after -// the decimal point. +// the decimal point using [rounding toward zero]. // If the given 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]. +// +// [rounding toward zero]: https://en.wikipedia.org/wiki/Rounding#Rounding_toward_zero func (a Amount) Trunc(scale int) Amount { - if scale < a.Curr().Scale() { - scale = a.Curr().Scale() + c, d := a.Curr(), a.Decimal() + if scale < c.Scale() { + scale = c.Scale() } - d := a.value - return newAmountUnsafe(a.Curr(), d.Trunc(scale)) + d = d.Trunc(scale) + return newAmountUnsafe(c, d) } -// TruncToCurr returns an amount truncated to the scale of its currency. -// See also method [Amount.SameScaleAsCurr]. +// TruncToCurr returns an amount truncated to the scale of its currency +// using [rounding toward zero]. +// See also methods [Amount.Trunc], [Amount.SameScaleAsCurr]. +// +// [rounding toward zero]: https://en.wikipedia.org/wiki/Rounding#Rounding_toward_zero func (a Amount) TruncToCurr() Amount { return a.Trunc(a.Curr().Scale()) } // Round returns an amount rounded to the specified number of digits after -// the decimal point. +// the decimal point using [rounding half to even] (banker's rounding). // If the given 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]. +// the amount will be rounded to the scale of the currency instead. +// See also methods [Amount.Rescale], [Amount.RoundToCurr]. +// +// [rounding half to even]: https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even func (a Amount) Round(scale int) Amount { - if scale < a.Curr().Scale() { - scale = a.Curr().Scale() + c, d := a.Curr(), a.Decimal() + if scale < c.Scale() { + scale = c.Scale() } - d := a.value - return newAmountUnsafe(a.Curr(), d.Round(scale)) + d = d.Round(scale) + return newAmountUnsafe(c, d) } -// RoundToCurr returns an amount rounded to the scale of its currency. -// See also method [Amount.SameScaleAsCurr]. +// RoundToCurr returns an amount rounded to the scale of its currency +// using [rounding half to even] (banker's rounding). +// See also methods [Amount.Round], [Amount.SameScaleAsCurr]. +// +// [rounding half to even]: https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even func (a Amount) RoundToCurr() Amount { return a.Round(a.Curr().Scale()) } +// Quantize returns an amount rescaled to the same scale as amount b. +// The currency and the sign of amount b are ignored. +// See also methods [Amount.Scale], [Amount.SameScale], [Amount.Rescale]. +// +// Quantize returns an error if the integer part of the result has more than +// ([decimal.MaxPrec] - b.Scale()) digits. +func (a Amount) Quantize(b Amount) (Amount, error) { + c, err := a.rescale(b.Scale()) + if err != nil { + return Amount{}, fmt.Errorf("quantizing %v to the scale of %v: %w", a, b, err) + } + return c, nil +} + // Rescale returns an amount rounded or zero-padded to the given number of digits // after the decimal point. // If the specified scale is less than the scale of the currency, -// the amount will be rounded to the currency's scale instead. +// the amount will be rounded to the scale of the currency instead. +// See also method [Amount.Round]. // -// Rescale returns an error if the integer part of the result exceeds -// the maximum precision, calculated as ([decimal.MaxPrec] - scale). +// Rescale returns an error if the integer part of the result more than +// ([decimal.MaxPrec] - scale) digits. func (a Amount) Rescale(scale int) (Amount, error) { - if scale < a.Curr().Scale() { - scale = a.Curr().Scale() - } - d := a.value - d, err := d.Rescale(scale) + c, err := a.rescale(scale) if err != nil { - return Amount{}, fmt.Errorf("rescaling %q to %v decimal places: %w", a, scale, err) + return Amount{}, fmt.Errorf("rescaling %v: %w", a, err) } - return NewAmount(a.Curr(), d) + return c, nil } -// 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.Rescale]. -// -// Quantize returns an error if: -// - amounts are denominated in different currencies. -// - the integer part of the result exceeds the maximum precision, -// calculated as ([decimal.MaxPrec] - b.Scale()). -func (a Amount) Quantize(b Amount) (Amount, error) { - if !a.SameCurr(b) { - return Amount{}, errCurrencyMismatch +func (a Amount) rescale(scale int) (Amount, error) { + c, d := a.Curr(), a.Decimal() + if scale < c.Scale() { + scale = c.Scale() + } + d, err := d.Rescale(scale) + if err != nil { + return Amount{}, err } - return a.Rescale(b.Scale()) + return newAmountSafe(c, d) } // Trim returns an amount with trailing zeros removed up to the given scale. -// If the given scale is less than the scale of the currency, -// the zeros will be removed up to the scale of the currency instead. +// If the given scale is less than the scale of the currency, the zeros will be +// removed up to the scale of the currency instead. // See also method [Amount.TrimToCurr]. func (a Amount) Trim(scale int) Amount { - if scale < a.Curr().Scale() { - scale = a.Curr().Scale() + c, d := a.Curr(), a.Decimal() + if scale < c.Scale() { + scale = c.Scale() } - d := a.value - return newAmountUnsafe(a.Curr(), d.Trim(scale)) + d = d.Trim(scale) + return newAmountUnsafe(c, d) } // TrimToCurr returns an amount with trailing zeros removed up the scale of its currency. +// See also method [Amount.Trim]. func (a Amount) TrimToCurr() Amount { return a.Trim(a.Curr().Scale()) } @@ -566,57 +829,83 @@ func (a Amount) SameCurr(b Amount) bool { } // SameScale returns true if amounts have the same scale. -// See also method [Amount.Scale]. +// See also methods [Amount.Scale], [Amount.Quantize]. func (a Amount) SameScale(b Amount) bool { - return a.Scale() == b.Scale() + d, e := a.Decimal(), b.Decimal() + return d.SameScale(e) } -// SameScaleAsCurr returns true if the scale of the amount matches the scale of its currency. -// See also methods [Amount.Scale] and [Currency.Scale]. +// SameScaleAsCurr returns true if the scale of the amount is equal to the scale of +// its currency. +// See also methods [Amount.Scale], [Currency.Scale], [Amount.RoundToCurr]. func (a Amount) SameScaleAsCurr() bool { return a.Scale() == a.Curr().Scale() } // String implements the [fmt.Stringer] interface and returns a string // representation of an amount. -// See also methods [Currency.String] and [Decimal.String]. +// See also methods [Currency.String], [Decimal.String], [Amount.Format]. // // [fmt.Stringer]: https://pkg.go.dev/fmt#Stringer // [Decimal.String]: https://pkg.go.dev/github.com/govalues/decimal#Decimal.String func (a Amount) String() string { - return a.Curr().String() + " " + a.value.String() + var b strings.Builder + b.WriteString(a.Curr().String()) + b.WriteByte(' ') + b.WriteString(a.Decimal().String()) + return b.String() } -// Cmp compares amounts numerically and returns: +// Cmp compares amounts and returns: // // -1 if a < b -// 0 if a == b +// 0 if a = b // +1 if a > b // +// See also methods [Amount.CmpAbs], [Amount.CmpTotal]. +// // Cmp returns an error if amounts are denominated in different currencies. func (a Amount) Cmp(b Amount) (int, error) { if !a.SameCurr(b) { - return 0, errCurrencyMismatch + return 0, fmt.Errorf("comparing [%v] and [%v]: %w", a, b, errCurrencyMismatch) } - d, e := a.value, b.value + d, e := a.Decimal(), b.Decimal() return d.Cmp(e), nil } +// CmpAbs compares absolute values of amounts and returns: +// +// -1 if |a| < |b| +// 0 if |a| = |b| +// +1 if |a| > |b| +// +// See also methods [Amount.Cmp], [Amount.CmpTotal]. +// +// CmpAbs returns an error if amounts are denominated in different currencies. +func (a Amount) CmpAbs(b Amount) (int, error) { + if !a.SameCurr(b) { + return 0, fmt.Errorf("comparing [abs(%v)] and [abs(%v)]: %w", a, b, errCurrencyMismatch) + } + d, e := a.Decimal(), b.Decimal() + return d.CmpAbs(e), nil +} + // 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 and a.scale > b.scale +// 0 if a = b and a.scale = b.scale +// +1 if a = b and a.scale < b.scale // +1 if a > b // +// See also methods [Amount.Cmp], [Amount.CmpAbs]. +// // CmpTotal returns an error if amounts are denominated in different currencies. -// See also method [Amount.Cmp]. func (a Amount) CmpTotal(b Amount) (int, error) { if !a.SameCurr(b) { - return 0, errCurrencyMismatch + return 0, fmt.Errorf("comparing [%v] and [%v]: %w", a, b, errCurrencyMismatch) } - d, e := a.value, b.value + d, e := a.Decimal(), b.Decimal() return d.CmpTotal(e), nil } @@ -625,10 +914,10 @@ func (a Amount) CmpTotal(b Amount) (int, error) { // // Min returns an error if amounts are denominated in different currencies. func (a Amount) Min(b Amount) (Amount, error) { - switch s, err := a.CmpTotal(b); { + switch c, err := a.CmpTotal(b); { case err != nil: return Amount{}, err - case s <= 0: + case c <= 0: // a <= b return a, nil default: return b, nil @@ -640,72 +929,120 @@ func (a Amount) Min(b Amount) (Amount, error) { // // Max returns an error if amounts are denominated in different currencies. func (a Amount) Max(b Amount) (Amount, error) { - switch s, err := a.CmpTotal(b); { + switch c, err := a.CmpTotal(b); { case err != nil: return Amount{}, err - case s >= 0: + case c >= 0: // a >= b return a, nil default: return b, nil } } +// Clamp compares amounts and returns: +// +// min if a < min +// max if a > max +// d otherwise +// +// See also method [Amount.CmpTotal]. +// +// Clamp returns an error if: +// - amounts are denominated in different currencies; +// - min is greater than max numerically. +func (a Amount) Clamp(min, max Amount) (Amount, error) { + switch c, err := min.Cmp(max); { + case err != nil: + return Amount{}, err + case c > 0: // min > max + return Amount{}, fmt.Errorf("clamping %v: invalid range", a) + } + switch c, err := min.CmpTotal(max); { + case err != nil: + return Amount{}, err + case c > 0: // min > max + // Numerically min and max are equal but have different scales. + // Swaping min and max to ensure total ordering. + min, max = max, min + } + switch c, err := a.CmpTotal(min); { + case err != nil: + return Amount{}, err + case c < 0: // a < min + return min, nil + } + switch c, err := a.CmpTotal(max); { + case err != nil: + return Amount{}, err + case c > 0: // a > max + return max, nil + } + return a, nil +} + // 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 +// | Verb | Example | Description | +// | ------ | ----------- | -------------------------- | +// | %s, %v | USD 5.678 | Currency and amount | +// | %q | "USD 5.678" | Quoted currency and amount | +// | %f | 5.678 | Amount | +// | %d | 568 | Amount in minor units | +// | %c | USD | Currency | // // 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. +// The default precision is equal to the actual scale of the amount. // // [format verbs]: https://pkg.go.dev/fmt#hdr-Printing // [fmt.Formatter]: https://pkg.go.dev/fmt#Formatter // //gocyclo:ignore func (a Amount) Format(state fmt.State, verb rune) { + c, d := a.Curr(), a.Decimal() + // Rescaling tzeroes := 0 if verb == 'f' || verb == 'F' || verb == 'd' || verb == 'D' { scale := 0 switch p, ok := state.Precision(); { case verb == 'd' || verb == 'D': - scale = a.Curr().Scale() + scale = c.Scale() case ok: scale = p case verb == 'f' || verb == 'F': - scale = a.Curr().Scale() + scale = d.Scale() + } + if scale < c.Scale() { + scale = c.Scale() } switch { - case scale < a.Scale(): - a = a.Round(scale) - case scale > a.Scale(): - tzeroes = scale - a.Scale() + case scale < d.Scale(): + d = d.Round(scale) + case scale > d.Scale(): + tzeroes = scale - d.Scale() } } // Integer and fractional digits intdigs, fracdigs := 0, 0 - switch aprec := a.Prec(); verb { + switch aprec := d.Prec(); verb { case 'c', 'C': // skip case 'd', 'D': intdigs = aprec - if a.IsZero() { + if d.IsZero() { intdigs++ // leading 0 } default: - fracdigs = a.Scale() + fracdigs = d.Scale() if aprec > fracdigs { intdigs = aprec - fracdigs } - if a.WithinOne() { + if d.WithinOne() { intdigs++ // leading 0 } } @@ -718,21 +1055,23 @@ func (a Amount) Format(state fmt.State, verb rune) { // Arithmetic sign rsign := 0 - if verb != 'c' && verb != 'C' && (a.IsNeg() || state.Flag('+') || state.Flag(' ')) { + if verb != 'c' && verb != 'C' && (d.IsNeg() || state.Flag('+') || state.Flag(' ')) { rsign = 1 } - // Currency symbols - curr := "" + // Currency code and delimiter + curr, currsyms, currdel := "", 0, 0 switch verb { case 'f', 'F', 'd', 'D': // skip case 'c', 'C': - curr = a.Curr().String() + curr = c.Code() + currsyms = len(curr) default: - curr = a.Curr().String() + " " + curr = c.Code() + currsyms = len(curr) + currdel = 1 } - currlen := len(curr) // Opening and closing quotes lquote, tquote := 0, 0 @@ -741,7 +1080,7 @@ func (a Amount) Format(state fmt.State, verb rune) { } // Calculating padding - width := lquote + rsign + intdigs + dpoint + fracdigs + tzeroes + currlen + tquote + width := lquote + currsyms + currdel + rsign + intdigs + dpoint + fracdigs + tzeroes + tquote lspaces, lzeroes, tspaces := 0, 0, 0 if w, ok := state.Width(); ok && w > width { switch { @@ -777,7 +1116,7 @@ func (a Amount) Format(state fmt.State, verb rune) { } // Fractional digits - coef := a.Coef() + coef := d.Coef() for i := 0; i < fracdigs; i++ { buf[pos] = byte(coef%10) + '0' pos-- @@ -805,7 +1144,7 @@ func (a Amount) Format(state fmt.State, verb rune) { // Arithmetic sign if rsign > 0 { - if a.IsNeg() { + if d.IsNeg() { buf[pos] = '-' } else if state.Flag(' ') { buf[pos] = ' ' @@ -815,8 +1154,14 @@ func (a Amount) Format(state fmt.State, verb rune) { pos-- } - // Currency symbols - for i := currlen; i > 0; i-- { + // Currency delimiter + if currdel > 0 { + buf[pos] = ' ' + pos-- + } + + // Currency code + for i := currsyms; i > 0; i-- { buf[pos] = curr[i-1] pos-- } diff --git a/amount_test.go b/amount_test.go index 4d9fe60..3fd0a7f 100644 --- a/amount_test.go +++ b/amount_test.go @@ -2,6 +2,7 @@ package money import ( "fmt" + "math" "reflect" "testing" "unsafe" @@ -27,8 +28,288 @@ func TestAmount_Sizeof(t *testing.T) { } func TestNewAmount(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + curr string + coef int64 + scale int + want string + }{ + {"JPY", math.MinInt64, 0, "-9223372036854775808"}, + {"JPY", math.MinInt64, 19, "-0.9223372036854775808"}, + {"USD", math.MinInt64, 2, "-92233720368547758.08"}, + {"USD", math.MinInt64, 19, "-0.9223372036854775808"}, + {"OMR", math.MinInt64, 3, "-9223372036854775.808"}, + {"OMR", math.MinInt64, 19, "-0.9223372036854775808"}, + {"JPY", 0, 0, "0"}, + {"USD", 0, 0, "0.00"}, + {"OMR", 0, 0, "0.000"}, + {"JPY", math.MaxInt64, 0, "9223372036854775807"}, + {"JPY", math.MaxInt64, 19, "0.9223372036854775807"}, + {"USD", math.MaxInt64, 2, "92233720368547758.07"}, + {"USD", math.MaxInt64, 19, "0.9223372036854775807"}, + {"OMR", math.MaxInt64, 3, "9223372036854775.807"}, + {"OMR", math.MaxInt64, 19, "0.9223372036854775807"}, + } + for _, tt := range tests { + got, err := NewAmount(tt.curr, tt.coef, tt.scale) + if err != nil { + t.Errorf("NewAmount(%q, %v, %v) failed: %v", tt.curr, tt.coef, tt.scale, err) + continue + } + want := MustParseAmount(tt.curr, tt.want) + if got != want { + t.Errorf("NewAmount(%q, %v, %v) = %q, want %q", tt.curr, tt.coef, tt.scale, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + curr string + coef int64 + scale int + }{ + "currency 1": {"UUU", 0, 0}, + "currency 2": {"ZZZ", 0, 0}, + "scale range 1": {"USD", 0, -1}, + "scale range 2": {"USD", 0, 20}, + "overflow 1": {"USD", math.MaxInt64, 0}, + "overflow 2": {"USD", math.MaxInt64, 1}, + "overflow 3": {"USD", math.MinInt64, 0}, + "overflow 4": {"USD", math.MinInt64, 1}, + "overflow 5": {"OMR", math.MaxInt64, 0}, + "overflow 6": {"OMR", math.MaxInt64, 1}, + "overflow 7": {"OMR", math.MaxInt64, 2}, + "overflow 8": {"OMR", math.MinInt64, 0}, + "overflow 9": {"OMR", math.MinInt64, 1}, + "overflow 10": {"OMR", math.MinInt64, 2}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + _, err := NewAmount(tt.curr, tt.coef, tt.scale) + if err == nil { + t.Errorf("NewAmount(%q, %v, %v) did not fail", tt.curr, tt.coef, tt.scale) + } + }) + } + }) +} + +func TestMustNewAmount(t *testing.T) { + t.Run("error", func(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("MustNewAmount(\"USD\", 0, -1) did not panic") + } + }() + MustNewAmount("USD", 0, -1) + }) +} + +func TestNewAmountFromInt64(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + curr string + whole, frac int64 + scale int + want string + }{ + // Zeroes + {"JPY", 0, 0, 0, "0"}, + {"JPY", 0, 0, 19, "0"}, + {"USD", 0, 0, 0, "0.00"}, + {"USD", 0, 0, 19, "0.00"}, + {"OMR", 0, 0, 0, "0.000"}, + {"OMR", 0, 0, 19, "0.000"}, + // Negatives + {"USD", -1, -1, 1, "-1.10"}, + {"USD", -1, -1, 2, "-1.01"}, + {"USD", -1, -1, 3, "-1.001"}, + {"USD", -1, -1, 18, "-1.000000000000000001"}, + // Positives + {"USD", 1, 1, 1, "1.10"}, + {"USD", 1, 1, 2, "1.01"}, + {"USD", 1, 1, 3, "1.001"}, + {"USD", 1, 100000000, 9, "1.10"}, + {"USD", 1, 1, 18, "1.000000000000000001"}, + {"USD", 1, 1, 19, "1.000000000000000000"}, + {"JPY", math.MaxInt64, math.MaxInt32, 10, "9223372036854775807"}, + {"JPY", math.MaxInt64, math.MaxInt64, 19, "9223372036854775808"}, + } + for _, tt := range tests { + got, err := NewAmountFromInt64(tt.curr, tt.whole, tt.frac, tt.scale) + if err != nil { + t.Errorf("NewAmountFromInt64(%q, %v, %v, %v) failed: %v", tt.curr, tt.whole, tt.frac, tt.scale, err) + continue + } + want := MustParseAmount(tt.curr, tt.want) + if got != want { + t.Errorf("NewAmountFromInt64(%q, %v, %v, %v) = %q, want %q", tt.curr, tt.whole, tt.frac, tt.scale, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + curr string + whole, frac int64 + scale int + }{ + "currency 1": {"UUU", 0, 0, 0}, + "currency 2": {"ZZZ", 0, 0, 0}, + "different signs 1": {"USD", -1, 1, 0}, + "fraction range 1": {"USD", 1, 1, 0}, + "scale range 1": {"USD", 1, 1, -1}, + "scale range 2": {"USD", 1, 0, -1}, + "scale range 3": {"USD", 1, 1, 20}, + "scale range 4": {"USD", 1, 0, 20}, + "overflow 1": {"USD", 100000000000000000, 100000000000000000, 18}, + "overflow 2": {"USD", 999999999999999999, 9, 1}, + "overflow 3": {"USD", 999999999999999999, 99, 2}, + "overflow 4": {"USD", math.MaxInt64, math.MaxInt32, 10}, + "overflow 5": {"OMR", math.MaxInt64, math.MaxInt32, 10}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + _, err := NewAmountFromInt64(tt.curr, tt.whole, tt.frac, tt.scale) + if err == nil { + t.Errorf("NewAmountFromInt64(%q, %v, %v, %v) did not fail", tt.curr, tt.whole, tt.frac, tt.scale) + } + }) + } + }) +} + +func TestNewAmountFromMinorUnits(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + curr string + units int64 + want string + }{ + {"JPY", math.MinInt64, "-9223372036854775808"}, + {"USD", math.MinInt64, "-92233720368547758.08"}, + {"OMR", math.MinInt64, "-9223372036854775.808"}, + {"JPY", 0, "0"}, + {"USD", 0, "0.00"}, + {"OMR", 0, "0.000"}, + {"JPY", math.MaxInt64, "9223372036854775807"}, + {"USD", math.MaxInt64, "92233720368547758.07"}, + {"OMR", math.MaxInt64, "9223372036854775.807"}, + } + for _, tt := range tests { + got, err := NewAmountFromMinorUnits(tt.curr, tt.units) + if err != nil { + t.Errorf("NewAmountFromMinorUnits(%q, %v) failed: %v", tt.curr, tt.units, err) + continue + } + want := MustParseAmount(tt.curr, tt.want) + if got != want { + t.Errorf("NewAmountFromMinorUnits(%q, %v) = %q, want %q", tt.curr, tt.units, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + curr string + units int64 + }{ + "currency 1": {"UUU", 0}, + "currency 2": {"ZZZ", 0}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + _, err := NewAmountFromMinorUnits(tt.curr, tt.units) + if err == nil { + t.Errorf("NewAmountFromMinorUnits(%q, %v) did not fail", tt.curr, tt.units) + } + }) + } + }) +} + +func TestNewAmountFromFloat64(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + curr string + f float64 + want string + }{ + // Zeroes + {"JPY", 0, "0"}, + {"USD", 0, "0.00"}, + {"OMR", 0, "0.000"}, + + // Smallest non-zero + {"JPY", math.SmallestNonzeroFloat64, "0.0000000000000000000"}, + {"USD", math.SmallestNonzeroFloat64, "0.0000000000000000000"}, + {"OMR", math.SmallestNonzeroFloat64, "0.0000000000000000000"}, + + // Powers of 10 + {"JPY", 1e-20, "0.0000000000000000000"}, + {"USD", 1e-20, "0.0000000000000000000"}, + {"OMR", 1e-20, "0.0000000000000000000"}, + + {"USD", 1e-19, "0.0000000000000000001"}, + {"USD", 1e-5, "0.00001"}, + {"USD", 1e-4, "0.0001"}, + {"USD", 1e-3, "0.001"}, + {"USD", 1e-2, "0.01"}, + {"USD", 1e-1, "0.1"}, + {"USD", 1e0, "1"}, + {"USD", 1e1, "10"}, + {"USD", 1e2, "100"}, + {"USD", 1e3, "1000"}, + {"USD", 1e4, "10000"}, + {"USD", 1e5, "100000"}, + + {"JPY", 1e18, "1000000000000000000"}, + {"USD", 1e16, "10000000000000000"}, + {"OMR", 1e15, "1000000000000000"}, + } + for _, tt := range tests { + got, err := NewAmountFromFloat64(tt.curr, tt.f) + if err != nil { + t.Errorf("NewAmountFromFloat64(%q, %v) failed: %v", tt.curr, tt.f, err) + continue + } + want := MustParseAmount(tt.curr, tt.want) + if got != want { + t.Errorf("NewAmountFromFloat64(%q, %v) = %q, want %q", tt.curr, tt.f, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + curr string + f float64 + }{ + "currency 1": {"UUU", 0}, + "currency 2": {"ZZZ", 0}, + "overflow 1": {"JPY", 1e19}, + "overflow 2": {"USD", 1e17}, + "overflow 3": {"OMR", 1e16}, + "special value 1": {"USD", math.NaN()}, + "special value 2": {"USD", math.Inf(1)}, + "special value 3": {"USD", math.Inf(-1)}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + _, err := NewAmountFromFloat64(tt.curr, tt.f) + if err == nil { + t.Errorf("NewAmountFromFloat64(%q, %v) did not fail", tt.curr, tt.f) + } + }) + } + }) +} + +func TestNewAmountFromDecimal(t *testing.T) { tests := []struct { - c Currency + curr Currency a string wantOk bool }{ @@ -41,12 +322,12 @@ func TestNewAmount(t *testing.T) { } for _, tt := range tests { amount := decimal.MustParse(tt.a) - _, err := NewAmount(tt.c, amount) + _, err := NewAmountFromDecimal(tt.curr, amount) if !tt.wantOk && err == nil { - t.Errorf("NewAmount(%v, %v) did not fail", tt.c, amount) + t.Errorf("NewAmountFromDecimal(%v, %v) did not fail", tt.curr, amount) } if tt.wantOk && err != nil { - t.Errorf("NewAmount(%v, %v) failed: %v", tt.c, amount, err) + t.Errorf("NewAmountFromDecimal(%v, %v) failed: %v", tt.curr, amount, err) } } } @@ -54,7 +335,7 @@ func TestNewAmount(t *testing.T) { func TestParseAmount(t *testing.T) { t.Run("success", func(t *testing.T) { tests := []struct { - c, a string + curr, a string wantCurr Currency wantCoef int64 wantScale int @@ -69,9 +350,9 @@ func TestParseAmount(t *testing.T) { {"USD", "1.00000", USD, 100000, 5}, } for _, tt := range tests { - got, err := ParseAmount(tt.c, tt.a) + got, err := ParseAmount(tt.curr, tt.a) if err != nil { - t.Errorf("ParseAmount(%q, %q) failed: %v", tt.c, tt.a, err) + t.Errorf("ParseAmount(%q, %q) failed: %v", tt.curr, tt.a, err) continue } wantAmount, err := decimal.New(tt.wantCoef, tt.wantScale) @@ -79,20 +360,20 @@ func TestParseAmount(t *testing.T) { t.Errorf("decimal.New(%v, %v) failed: %v", tt.wantCoef, tt.wantScale, err) continue } - want, err := NewAmount(tt.wantCurr, wantAmount) + want, err := NewAmountFromDecimal(tt.wantCurr, wantAmount) if err != nil { t.Errorf("NewAmount(%v, %v) failed: %v", tt.wantCurr, wantAmount, err) continue } if got != want { - t.Errorf("ParseAmount(%q, %q) = %q, want %q", tt.c, tt.a, got, want) + t.Errorf("ParseAmount(%q, %q) = %q, want %q", tt.curr, tt.a, got, want) } } }) t.Run("error", func(t *testing.T) { tests := map[string]struct { - c, a string + curr, a string }{ "currency 1": {"///", "1"}, "currency 2": {"ZZZ", "1.0"}, @@ -102,18 +383,29 @@ func TestParseAmount(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - _, err := ParseAmount(tt.c, tt.a) + _, err := ParseAmount(tt.curr, tt.a) if err == nil { - t.Errorf("ParseAmount(%q, %q) did not fail", tt.c, tt.a) + t.Errorf("ParseAmount(%q, %q) did not fail", tt.curr, tt.a) } }) } }) } +func TestMustParseAmount(t *testing.T) { + t.Run("error", func(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("MustParseAmount(\"UUU\", \".\") did not panic") + } + }() + MustParseAmount("UUU", ".") + }) +} + func TestAmount_MinorUnits(t *testing.T) { tests := []struct { - c, a string + curr, a string wantUnits int64 wantOk bool }{ @@ -147,6 +439,18 @@ func TestAmount_MinorUnits(t *testing.T) { {"USD", "1.5678", 157, true}, {"USD", "1.56789", 157, true}, + {"USD", "-6", -600, true}, + {"USD", "-0.6", -60, true}, + {"USD", "-0.06", -6, true}, + {"USD", "-0.006", -1, true}, + {"USD", "-0.0006", 0, true}, + + {"USD", "-4", -400, true}, + {"USD", "-0.4", -40, true}, + {"USD", "-0.04", -4, true}, + {"USD", "-0.004", 0, true}, + {"USD", "-0.0004", 0, true}, + // Minimal value {"USD", "-92233720368547758.08", -9223372036854775808, true}, {"USD", "-92233720368547758.09", 0, false}, @@ -156,7 +460,7 @@ func TestAmount_MinorUnits(t *testing.T) { {"USD", "92233720368547758.08", 0, false}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) + a := MustParseAmount(tt.curr, tt.a) gotUnits, gotOk := a.MinorUnits() if gotUnits != tt.wantUnits || gotOk != tt.wantOk { t.Errorf("%q.MinorUnits() = [%v %v], want [%v %v]", a, gotUnits, gotOk, tt.wantUnits, tt.wantOk) @@ -166,8 +470,8 @@ func TestAmount_MinorUnits(t *testing.T) { func TestAmount_SameScaleAsCurr(t *testing.T) { tests := []struct { - c, a string - want bool + curr, a string + want bool }{ {"USD", "1.00", true}, {"USD", "1.000", false}, @@ -175,7 +479,7 @@ func TestAmount_SameScaleAsCurr(t *testing.T) { {"USD", "1.00000", false}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) + a := MustParseAmount(tt.curr, tt.a) got := a.SameScaleAsCurr() if got != tt.want { t.Errorf("%q.SameScaleAsCurr() = %v, want %v", a, got, tt.want) @@ -194,7 +498,7 @@ func MustParseAmountSlice(curr string, amounts []string) []Amount { func TestAmount_Add(t *testing.T) { t.Run("success", func(t *testing.T) { tests := []struct { - c, a, b, want string + curr, a, b, want string }{ // There are few test cases here since Decimal.Add // is already tested by the cases in the decimal package. @@ -215,14 +519,14 @@ func TestAmount_Add(t *testing.T) { {"USD", "99999999999999999.99", "-0.01", "99999999999999999.98"}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) - b := MustParseAmount(tt.c, tt.b) + a := MustParseAmount(tt.curr, tt.a) + b := MustParseAmount(tt.curr, tt.b) got, err := a.Add(b) if err != nil { t.Errorf("%q.Add(%q) failed: %v", a, b, err) continue } - want := MustParseAmount(tt.c, tt.want) + want := MustParseAmount(tt.curr, tt.want) if got != want { t.Errorf("%q.Add(%q) = %q, want %q", a, b, got, want) } @@ -231,7 +535,7 @@ func TestAmount_Add(t *testing.T) { t.Run("error", func(t *testing.T) { tests := map[string]struct { - ca, a, cb, b string + curra, a, currb, b string }{ "currency 1": {"USD", "1", "JPY", "1"}, "currency 2": {"USD", "1", "EUR", "1"}, @@ -241,8 +545,8 @@ func TestAmount_Add(t *testing.T) { "overflow 4": {"USD", "-99999999999999999.99", "USD", "-0.006"}, } for _, tt := range tests { - a := MustParseAmount(tt.ca, tt.a) - b := MustParseAmount(tt.cb, tt.b) + a := MustParseAmount(tt.curra, tt.a) + b := MustParseAmount(tt.currb, tt.b) _, err := a.Add(b) if err == nil { t.Errorf("%q.Add(%q) did not fail", a, b) @@ -251,10 +555,128 @@ func TestAmount_Add(t *testing.T) { }) } +func TestAmount_Sub(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + curr, a, b, want string + }{ + // There are few test cases here since Decimal.Sub + // is already tested by the cases in the decimal package. + {"USD", "1", "1", "0"}, + {"USD", "2", "1", "1"}, + {"USD", "5.75", "3.3", "2.45"}, + {"USD", "5", "3", "2"}, + {"USD", "-5", "3", "-8"}, + {"USD", "-7", "2.5", "-9.5"}, + {"USD", "0.7", "0.3", "0.4"}, + {"USD", "1.25", "1.25", "0.00"}, + {"USD", "1.1", "0.11", "0.99"}, + {"USD", "1.234567890", "1.000000000", "0.234567890"}, + {"USD", "1.234567890", "1.000000110", "0.234567780"}, + {"USD", "99999999999999999.99", "0.004", "99999999999999999.99"}, + {"USD", "-99999999999999999.99", "-0.004", "-99999999999999999.99"}, + {"USD", "0.01", "99999999999999999.99", "-99999999999999999.98"}, + {"USD", "99999999999999999.99", "0.01", "99999999999999999.98"}, + } + for _, tt := range tests { + a := MustParseAmount(tt.curr, tt.a) + b := MustParseAmount(tt.curr, tt.b) + got, err := a.Sub(b) + if err != nil { + t.Errorf("%q.Sub(%q) failed: %v", a, b, err) + continue + } + want := MustParseAmount(tt.curr, tt.want) + if got != want { + t.Errorf("%q.Sub(%q) = %q, want %q", a, b, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + curra, a, currb, b string + }{ + "currency 1": {"USD", "1", "JPY", "1"}, + "currency 2": {"USD", "1", "EUR", "1"}, + "overflow 1": {"USD", "99999999999999999.99", "USD", "-0.01"}, + "overflow 2": {"USD", "99999999999999999.99", "USD", "-0.006"}, + "overflow 3": {"USD", "-99999999999999999.99", "USD", "0.01"}, + "overflow 4": {"USD", "-99999999999999999.99", "USD", "0.006"}, + } + for _, tt := range tests { + a := MustParseAmount(tt.curra, tt.a) + b := MustParseAmount(tt.currb, tt.b) + _, err := a.Sub(b) + if err == nil { + t.Errorf("%q.Sub(%q) did not fail", a, b) + } + } + }) +} + +func TestAmount_SubAbs(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + curr, a, b, want string + }{ + {"USD", "1", "1", "0"}, + {"USD", "2", "1", "1"}, + {"USD", "5.75", "3.3", "2.45"}, + {"USD", "5", "3", "2"}, + {"USD", "-5", "3", "8"}, + {"USD", "-7", "2.5", "9.5"}, + {"USD", "0.7", "0.3", "0.4"}, + {"USD", "1.25", "1.25", "0.00"}, + {"USD", "1.1", "0.11", "0.99"}, + {"USD", "1.234567890", "1.000000000", "0.234567890"}, + {"USD", "1.234567890", "1.000000110", "0.234567780"}, + {"USD", "99999999999999999.99", "0.004", "99999999999999999.99"}, + {"USD", "-99999999999999999.99", "-0.004", "99999999999999999.99"}, + {"USD", "0.01", "99999999999999999.99", "99999999999999999.98"}, + {"USD", "99999999999999999.99", "0.01", "99999999999999999.98"}, + } + for _, tt := range tests { + a := MustParseAmount(tt.curr, tt.a) + b := MustParseAmount(tt.curr, tt.b) + got, err := a.SubAbs(b) + if err != nil { + t.Errorf("%q.SubAbs(%q) failed: %v", a, b, err) + continue + } + want := MustParseAmount(tt.curr, tt.want) + if got != want { + t.Errorf("%q.SubAbs(%q) = %q, want %q", a, b, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + curra, a, currb, b string + }{ + "currency 1": {"USD", "1", "JPY", "1"}, + "currency 2": {"USD", "1", "EUR", "1"}, + "overflow 1": {"USD", "99999999999999999.99", "USD", "-0.01"}, + "overflow 2": {"USD", "99999999999999999.99", "USD", "-0.006"}, + "overflow 3": {"USD", "-99999999999999999.99", "USD", "0.01"}, + "overflow 4": {"USD", "-99999999999999999.99", "USD", "0.006"}, + } + for _, tt := range tests { + a := MustParseAmount(tt.curra, tt.a) + b := MustParseAmount(tt.currb, tt.b) + _, err := a.SubAbs(b) + if err == nil { + t.Errorf("%q.SubAbs(%q) did not fail", a, b) + } + } + }) +} + func TestAmount_FMA(t *testing.T) { t.Run("success", func(t *testing.T) { tests := []struct { - c, a, e, b, want string + curr, a, e, b, want string }{ // There are few test cases here since Decimal.FMA // is already tested by the cases in the decimal package. @@ -293,15 +715,15 @@ func TestAmount_FMA(t *testing.T) { {"USD", "0.70", "1.05", "0", "0.7350"}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) + a := MustParseAmount(tt.curr, tt.a) e := decimal.MustParse(tt.e) - b := MustParseAmount(tt.c, tt.b) + b := MustParseAmount(tt.curr, tt.b) got, err := a.FMA(e, b) if err != nil { t.Errorf("%q.FMA(%q, %q) failed: %v", a, e, b, err) continue } - want := MustParseAmount(tt.c, tt.want) + want := MustParseAmount(tt.curr, tt.want) if got != want { t.Errorf("%q.FMA(%q, %q) = %q, want %q", a, e, b, got, want) } @@ -310,7 +732,7 @@ func TestAmount_FMA(t *testing.T) { t.Run("error", func(t *testing.T) { tests := map[string]struct { - ca, a, e, cb, b string + curra, a, e, currb, b string }{ "overflow 1": {"JPY", "1", "9999999999999999999", "JPY", "1"}, "overflow 2": {"JPY", "1", "9999999999999999999", "JPY", "0.6"}, @@ -321,9 +743,9 @@ func TestAmount_FMA(t *testing.T) { "currency 1": {"JPY", "1", "1", "USD", "1"}, } for _, tt := range tests { - a := MustParseAmount(tt.ca, tt.a) + a := MustParseAmount(tt.curra, tt.a) e := decimal.MustParse(tt.e) - b := MustParseAmount(tt.cb, tt.b) + b := MustParseAmount(tt.currb, tt.b) _, err := a.FMA(e, b) if err == nil { t.Errorf("%q.FMA(%q, %q) did not fail", a, e, b) @@ -335,7 +757,7 @@ func TestAmount_FMA(t *testing.T) { func TestAmount_Rat(t *testing.T) { t.Run("success", func(t *testing.T) { tests := []struct { - c, a, b, want string + curr, a, b, want string }{ // There are few test cases here since Decimal.Quo // is already tested by the cases in the decimal package. @@ -359,8 +781,8 @@ func TestAmount_Rat(t *testing.T) { {"USD", "99999999999999999.99", "99999999999999999.99", "1"}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) - b := MustParseAmount(tt.c, tt.b) + a := MustParseAmount(tt.curr, tt.a) + b := MustParseAmount(tt.curr, tt.b) got, err := a.Rat(b) if err != nil { t.Errorf("%q.Rat(%q) failed: %v", a, b, err) @@ -375,14 +797,14 @@ func TestAmount_Rat(t *testing.T) { t.Run("error", func(t *testing.T) { tests := map[string]struct { - ca, a, cb, b string + curra, a, currb, b string }{ "overflow 1": {"USD", "10000000000000000", "USD", "0.001"}, "zero 1": {"USD", "1", "USD", "0"}, } for _, tt := range tests { - a := MustParseAmount(tt.ca, tt.a) - b := MustParseAmount(tt.cb, tt.b) + a := MustParseAmount(tt.curra, tt.a) + b := MustParseAmount(tt.currb, tt.b) _, err := a.Rat(b) if err == nil { t.Errorf("%q.Rat(%q) did not fail", a, b) @@ -394,7 +816,7 @@ func TestAmount_Rat(t *testing.T) { func TestAmount_Quo(t *testing.T) { t.Run("success", func(t *testing.T) { tests := []struct { - c, a, e, want string + curr, a, e, want string }{ // There are few test cases here since Decimal.Quo // is already tested by the cases in the decimal package. @@ -418,14 +840,14 @@ func TestAmount_Quo(t *testing.T) { {"USD", "99999999999999999.99", "99999999999999999.99", "1"}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) + a := MustParseAmount(tt.curr, tt.a) e := decimal.MustParse(tt.e) got, err := a.Quo(e) if err != nil { t.Errorf("%q.Quo(%q) failed: %v", a, e, err) continue } - want := MustParseAmount(tt.c, tt.want) + want := MustParseAmount(tt.curr, tt.want) if got != want { t.Errorf("%q.Quo(%q) = %q, want %q", a, e, got, want) } @@ -434,13 +856,13 @@ func TestAmount_Quo(t *testing.T) { t.Run("error", func(t *testing.T) { tests := map[string]struct { - c, a, e string + curr, a, e string }{ "zero 1": {"USD", "1", "0"}, "overflow 1": {"USD", "99999999999999999", "0.1"}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) + a := MustParseAmount(tt.curr, tt.a) e := decimal.MustParse(tt.e) _, err := a.Quo(e) if err == nil { @@ -453,13 +875,17 @@ func TestAmount_Quo(t *testing.T) { func TestAmount_QuoRem(t *testing.T) { t.Run("success", func(t *testing.T) { tests := []struct { - c, a, e, wantQuo, wantRem string + curr, a, e, wantQuo, wantRem string }{ + {"USD", "0.00", "1", "0.00", "0.00"}, {"USD", "1.00", "1", "1.00", "0.00"}, + {"USD", "1.01", "1", "1.01", "0.00"}, {"USD", "2.00", "1", "2.00", "0.00"}, + {"USD", "2.01", "1", "2.01", "0.00"}, {"USD", "1.00", "2", "0.50", "0.00"}, + {"USD", "1.01", "2", "0.50", "0.01"}, {"USD", "2.00", "2", "1.00", "0.00"}, - {"USD", "0.00", "1", "0.00", "0.00"}, + {"USD", "2.01", "2", "1.00", "0.01"}, {"USD", "1.510", "3", "0.50", "0.010"}, {"USD", "3.333", "3", "1.11", "0.003"}, {"USD", "2.401", "1", "2.40", "0.001"}, @@ -468,15 +894,15 @@ func TestAmount_QuoRem(t *testing.T) { {"USD", "-2.401", "-1", "2.40", "-0.001"}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) + a := MustParseAmount(tt.curr, tt.a) e := decimal.MustParse(tt.e) gotQuo, gotRem, err := a.QuoRem(e) if err != nil { t.Errorf("%q.QuoRem(%q) failed: %v", a, e, err) continue } - wantQuo := MustParseAmount(tt.c, tt.wantQuo) - wantRem := MustParseAmount(tt.c, tt.wantRem) + wantQuo := MustParseAmount(tt.curr, tt.wantQuo) + wantRem := MustParseAmount(tt.curr, tt.wantRem) if gotQuo != wantQuo || gotRem != wantRem { t.Errorf("%q.QuoRem(%q) = [%q %q], want [%q %q]", a, e, gotQuo, gotRem, wantQuo, wantRem) } @@ -485,13 +911,13 @@ func TestAmount_QuoRem(t *testing.T) { t.Run("error", func(t *testing.T) { tests := map[string]struct { - c, a, e string + curr, a, e string }{ "zero 1": {"USD", "1", "0"}, "overflow 1": {"USD", "99999999999999999", "0.1"}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) + a := MustParseAmount(tt.curr, tt.a) e := decimal.MustParse(tt.e) _, _, err := a.QuoRem(e) if err == nil { @@ -504,7 +930,7 @@ func TestAmount_QuoRem(t *testing.T) { func TestAmount_Mul(t *testing.T) { t.Run("success", func(t *testing.T) { tests := []struct { - c, a, e, want string + curr, a, e, want string }{ // There are few test cases here since Decimal.Mul // is already tested by the cases in the decimal package. @@ -524,14 +950,14 @@ func TestAmount_Mul(t *testing.T) { {"USD", "0.70", "1.05", "0.7350"}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) + a := MustParseAmount(tt.curr, tt.a) e := decimal.MustParse(tt.e) got, err := a.Mul(e) if err != nil { t.Errorf("%q.Mul(%q) failed: %v", a, e, err) continue } - want := MustParseAmount(tt.c, tt.want) + want := MustParseAmount(tt.curr, tt.want) if got != want { t.Errorf("%q.Mul(%q) = %q, want %q", a, e, got, want) } @@ -540,13 +966,13 @@ func TestAmount_Mul(t *testing.T) { t.Run("error", func(t *testing.T) { tests := map[string]struct { - c, a, e string + curr, a, e string }{ "overflow 1": {"USD", "10000000000", "1000000000"}, "overflow 2": {"USD", "10000000000000000", "1000"}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) + a := MustParseAmount(tt.curr, tt.a) e := decimal.MustParse(tt.e) _, err := a.Mul(e) if err == nil { @@ -559,9 +985,9 @@ func TestAmount_Mul(t *testing.T) { func TestAmount_Split(t *testing.T) { t.Run("success", func(t *testing.T) { tests := []struct { - c, a string - parts int - want []string + curr, a string + parts int + want []string }{ {"OMR", "0.0001", 3, []string{"0.0001", "0.0000", "0.0000"}}, {"OMR", "-0.0001", 3, []string{"-0.0001", "0.0000", "0.0000"}}, @@ -593,13 +1019,13 @@ func TestAmount_Split(t *testing.T) { {"USD", "-1.01", 6, []string{"-0.17", "-0.17", "-0.17", "-0.17", "-0.17", "-0.16"}}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) + a := MustParseAmount(tt.curr, tt.a) got, err := a.Split(tt.parts) if err != nil { t.Errorf("%q.Split(%v) failed: %v", a, tt.parts, err) continue } - want := MustParseAmountSlice(tt.c, tt.want) + want := MustParseAmountSlice(tt.curr, tt.want) if !reflect.DeepEqual(got, want) { t.Errorf("%q.Split(%v) = %v, want %v", a, tt.parts, got, want) } @@ -618,7 +1044,7 @@ func TestAmount_Split(t *testing.T) { func TestAmount_String(t *testing.T) { tests := []struct { - c, a, want string + curr, a, want string }{ // Zeroes {"JPY", "0", "JPY 0"}, @@ -638,7 +1064,7 @@ func TestAmount_String(t *testing.T) { {"USD", "1", "USD 1.00"}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) + a := MustParseAmount(tt.curr, tt.a) got := a.String() if got != tt.want { t.Errorf("%q.String() = %q, want %q", a, got, tt.want) @@ -648,7 +1074,7 @@ func TestAmount_String(t *testing.T) { func TestAmount_Format(t *testing.T) { tests := []struct { - c, a, format, want string + curr, a, format, want string }{ // %T verb {"USD", "100.00", "%T", "money.Amount"}, @@ -692,19 +1118,19 @@ func TestAmount_Format(t *testing.T) { {"USD", "100.00", "%-13v", "USD 100.00 "}, {"USD", "100.00", "%+-015v", "USD +100.00 "}, // '0' is ignored // %f verb - {"JPY", "0.00", "%f", "0"}, // default precision is 0 (JPY scale) - {"JPY", "0.01", "%f", "0"}, - {"JPY", "100.00", "%f", "100"}, - {"OMR", "0.00", "%f", "0.000"}, // default precision is 3 (OMR scale) + {"JPY", "0.00", "%f", "0.00"}, + {"JPY", "0.01", "%f", "0.01"}, + {"JPY", "100.00", "%f", "100.00"}, + {"OMR", "0.00", "%f", "0.000"}, {"OMR", "0.01", "%f", "0.010"}, {"OMR", "100.00", "%f", "100.000"}, - {"USD", "0.00", "%f", "0.00"}, // default precision is 2 (USD scale) + {"USD", "0.00", "%f", "0.00"}, {"USD", "0.01", "%f", "0.01"}, {"USD", "100.00", "%f", "100.00"}, - {"USD", "9.996208266660", "%f", "10.00"}, - {"USD", "0.9996208266660", "%f", "1.00"}, - {"USD", "0.09996208266660", "%f", "0.10"}, - {"USD", "0.009996208266660", "%f", "0.01"}, + {"USD", "9.996208266660", "%.2f", "10.00"}, + {"USD", "0.9996208266660", "%.2f", "1.00"}, + {"USD", "0.09996208266660", "%.2f", "0.10"}, + {"USD", "0.009996208266660", "%.2f", "0.01"}, {"USD", "100.00", "%+f", "+100.00"}, {"USD", "100.00", "% f", " 100.00"}, {"USD", "100.00", "%.1f", "100.00"}, // precision cannot be smaller than curr scale @@ -731,6 +1157,7 @@ func TestAmount_Format(t *testing.T) { {"USD", "0.9996208266660", "%d", "100"}, {"USD", "0.09996208266660", "%d", "10"}, {"USD", "0.009996208266660", "%d", "1"}, + {"USD", "0.0009996208266660", "%d", "0"}, {"USD", "100.00", "%+d", "+10000"}, {"USD", "100.00", "% d", " 10000"}, {"USD", "100.00", "%.6d", "10000"}, // precision is ignored @@ -761,7 +1188,7 @@ func TestAmount_Format(t *testing.T) { {"USD", "12.34", "%X", "%!X(money.Amount=USD 12.34)"}, } for _, tt := range tests { - a := MustParseAmount(tt.c, tt.a) + a := MustParseAmount(tt.curr, tt.a) got := fmt.Sprintf(tt.format, a) if got != tt.want { t.Errorf("fmt.Sprintf(%q, %q) = %q, want %q", tt.format, a, got, tt.want) @@ -772,8 +1199,8 @@ func TestAmount_Format(t *testing.T) { func TestAmount_Cmp(t *testing.T) { t.Run("success", func(t *testing.T) { tests := []struct { - c, a, b string - want int + curr, a, b string + want int }{ {"USD", "-2", "-2", 0}, {"USD", "-2", "-1", -1}, @@ -812,8 +1239,8 @@ func TestAmount_Cmp(t *testing.T) { {"USD", "0.9999999999999999999", "99999999999999999.99", -1}, } for _, tt := range tests { - d := MustParseAmount(tt.c, tt.a) - e := MustParseAmount(tt.c, tt.b) + d := MustParseAmount(tt.curr, tt.a) + e := MustParseAmount(tt.curr, tt.b) got, err := d.Cmp(e) if err != nil { t.Errorf("%q.Cmp(%q) failed: %v", d, e, err) @@ -835,11 +1262,77 @@ func TestAmount_Cmp(t *testing.T) { }) } +func TestAmount_CmpAbs(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + curr, a, b string + want int + }{ + {"USD", "-2", "-2", 0}, + {"USD", "-2", "-1", 1}, + {"USD", "-2", "0", 1}, + {"USD", "-2", "1", 1}, + {"USD", "-2", "2", 0}, + {"USD", "-1", "-2", -1}, + {"USD", "-1", "-1", 0}, + {"USD", "-1", "0", 1}, + {"USD", "-1", "1", 0}, + {"USD", "-1", "2", -1}, + {"USD", "0", "-2", -1}, + {"USD", "0", "-1", -1}, + {"USD", "0", "0", 0}, + {"USD", "0", "1", -1}, + {"USD", "0", "2", -1}, + {"USD", "1", "-2", -1}, + {"USD", "1", "-1", 0}, + {"USD", "1", "0", 1}, + {"USD", "1", "1", 0}, + {"USD", "1", "2", -1}, + {"USD", "2", "-2", 0}, + {"USD", "2", "-1", 1}, + {"USD", "2", "0", 1}, + {"USD", "2", "1", 1}, + {"JPY", "2", "2", 0}, + {"JPY", "2", "2.0", 0}, + {"JPY", "2", "2.00", 0}, + {"JPY", "2", "2.000", 0}, + {"JPY", "2", "2.0000", 0}, + {"JPY", "2", "2.00000", 0}, + {"JPY", "2", "2.000000", 0}, + {"JPY", "2", "2.0000000", 0}, + {"JPY", "2", "2.00000000", 0}, + {"USD", "99999999999999999.99", "0.9999999999999999999", 1}, + {"USD", "0.9999999999999999999", "99999999999999999.99", -1}, + } + for _, tt := range tests { + d := MustParseAmount(tt.curr, tt.a) + e := MustParseAmount(tt.curr, tt.b) + got, err := d.CmpAbs(e) + if err != nil { + t.Errorf("%q.CmpAbs(%q) failed: %v", d, e, err) + continue + } + if got != tt.want { + t.Errorf("%q.CmpAbs(%q) = %v, want %v", d, e, got, tt.want) + } + } + }) + + t.Run("error", func(t *testing.T) { + a := MustParseAmount("USD", "1") + b := MustParseAmount("JPY", "1") + _, err := a.CmpAbs(b) + if err == nil { + t.Errorf("%q.CmpAbs(%q) did not fail", a, b) + } + }) +} + func TestAmount_CmpTotal(t *testing.T) { t.Run("success", func(t *testing.T) { tests := []struct { - c, a, b string - want int + curr, a, b string + want int }{ {"USD", "-2", "-2", 0}, {"USD", "-2", "-1", -1}, @@ -878,8 +1371,8 @@ func TestAmount_CmpTotal(t *testing.T) { {"USD", "0.9999999999999999999", "99999999999999999.99", -1}, } for _, tt := range tests { - d := MustParseAmount(tt.c, tt.a) - e := MustParseAmount(tt.c, tt.b) + d := MustParseAmount(tt.curr, tt.a) + e := MustParseAmount(tt.curr, tt.b) got, err := d.CmpTotal(e) if err != nil { t.Errorf("%q.CmpTotal(%q) failed: %v", d, e, err) @@ -900,3 +1393,362 @@ func TestAmount_CmpTotal(t *testing.T) { } }) } + +func TestAmount_Min(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + curr, a, b, want string + }{ + {"USD", "-2", "-2", "-2"}, + {"USD", "-2", "-1", "-2"}, + {"USD", "-2", "0", "-2"}, + {"USD", "-2", "1", "-2"}, + {"USD", "-2", "2", "-2"}, + {"USD", "-1", "-2", "-2"}, + {"USD", "-1", "-1", "-1"}, + {"USD", "-1", "0", "-1"}, + {"USD", "-1", "1", "-1"}, + {"USD", "-1", "2", "-1"}, + {"USD", "0", "-2", "-2"}, + {"USD", "0", "-1", "-1"}, + {"USD", "0", "0", "0"}, + {"USD", "0", "1", "0"}, + {"USD", "0", "2", "0"}, + {"USD", "1", "-2", "-2"}, + {"USD", "1", "-1", "-1"}, + {"USD", "1", "0", "0"}, + {"USD", "1", "1", "1"}, + {"USD", "1", "2", "1"}, + {"USD", "2", "-2", "-2"}, + {"USD", "2", "-1", "-1"}, + {"USD", "2", "0", "0"}, + {"USD", "2", "1", "1"}, + {"USD", "2", "2", "2"}, + {"USD", "0.000", "0.0", "0.000"}, + {"USD", "0.0", "0.000", "0.000"}, + {"USD", "-0.000", "-0.0", "0.000"}, + {"USD", "-0.0", "-0.000", "0.000"}, + {"USD", "1.23", "1.2300", "1.2300"}, + {"USD", "1.2300", "1.23", "1.2300"}, + {"USD", "-1.23", "-1.2300", "-1.2300"}, + {"USD", "-1.2300", "-1.23", "-1.2300"}, + } + for _, tt := range tests { + a := MustParseAmount(tt.curr, tt.a) + b := MustParseAmount(tt.curr, tt.b) + got, err := a.Min(b) + if err != nil { + t.Errorf("%q.Min(%q) failed: %v", a, b, err) + continue + } + want := MustParseAmount(tt.curr, tt.want) + if got != want { + t.Errorf("%q.Min(%q) = %q, want %q", a, b, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + a := MustParseAmount("USD", "1") + b := MustParseAmount("JPY", "1") + _, err := a.Min(b) + if err == nil { + t.Errorf("%q.Min(%q) did not fail", a, b) + } + }) +} + +func TestAmount_Max(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + curr, a, b, want string + }{ + {"USD", "-2", "-2", "-2"}, + {"USD", "-2", "-1", "-1"}, + {"USD", "-2", "0", "0"}, + {"USD", "-2", "1", "1"}, + {"USD", "-2", "2", "2"}, + {"USD", "-1", "-2", "-1"}, + {"USD", "-1", "-1", "-1"}, + {"USD", "-1", "0", "0"}, + {"USD", "-1", "1", "1"}, + {"USD", "-1", "2", "2"}, + {"USD", "0", "-2", "0"}, + {"USD", "0", "-1", "0"}, + {"USD", "0", "0", "0"}, + {"USD", "0", "1", "1"}, + {"USD", "0", "2", "2"}, + {"USD", "1", "-2", "1"}, + {"USD", "1", "-1", "1"}, + {"USD", "1", "0", "1"}, + {"USD", "1", "1", "1"}, + {"USD", "1", "2", "2"}, + {"USD", "2", "-2", "2"}, + {"USD", "2", "-1", "2"}, + {"USD", "2", "0", "2"}, + {"USD", "2", "1", "2"}, + {"USD", "2", "2", "2"}, + {"USD", "0.000", "0.0", "0.0"}, + {"USD", "0.0", "0.000", "0.0"}, + {"USD", "-0.000", "-0.0", "0.0"}, + {"USD", "-0.0", "-0.000", "0.0"}, + {"USD", "1.23", "1.2300", "1.23"}, + {"USD", "1.2300", "1.23", "1.23"}, + {"USD", "-1.23", "-1.2300", "-1.23"}, + {"USD", "-1.2300", "-1.23", "-1.23"}, + } + for _, tt := range tests { + a := MustParseAmount(tt.curr, tt.a) + b := MustParseAmount(tt.curr, tt.b) + got, err := a.Max(b) + if err != nil { + t.Errorf("%q.Max(%q) failed: %v", a, b, err) + continue + } + want := MustParseAmount(tt.curr, tt.want) + if got != want { + t.Errorf("%q.Max(%q) = %q, want %q", a, b, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + a := MustParseAmount("USD", "1") + b := MustParseAmount("JPY", "1") + _, err := a.Max(b) + if err == nil { + t.Errorf("%q.Max(%q) did not fail", a, b) + } + }) +} + +func TestAmount_Clamp(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + curr, a, min, max, want string + }{ + {"USD", "0", "-2", "-1", "-1"}, + {"USD", "0", "-1", "1", "0"}, + {"USD", "0", "1", "2", "1"}, + {"USD", "0.000", "0.0", "0.000", "0.000"}, + {"USD", "0.000", "0.000", "0.0", "0.000"}, + {"USD", "0.0", "0.0", "0.000", "0.0"}, + {"USD", "0.0", "0.000", "0.0", "0.0"}, + {"USD", "0.000", "0.000", "1", "0.000"}, + {"USD", "0.000", "0.0", "1", "0.0"}, + {"USD", "0.0", "0.000", "1", "0.0"}, + {"USD", "0.0", "0.0", "1", "0.0"}, + {"USD", "0.000", "-1", "0.000", "0.000"}, + {"USD", "0.000", "-1", "0.0", "0.000"}, + {"USD", "0.0", "-1", "0.000", "0.000"}, + {"USD", "0.0", "-1", "0.0", "0.0"}, + {"USD", "1.2300", "1.2300", "2", "1.2300"}, + {"USD", "1.2300", "1.23", "2", "1.23"}, + {"USD", "1.23", "1.2300", "2", "1.23"}, + {"USD", "1.23", "1.23", "2", "1.23"}, + {"USD", "1.2300", "1", "1.2300", "1.2300"}, + {"USD", "1.2300", "1", "1.23", "1.2300"}, + {"USD", "1.23", "1", "1.2300", "1.2300"}, + {"USD", "1.23", "1", "1.23", "1.23"}, + } + for _, tt := range tests { + a := MustParseAmount(tt.curr, tt.a) + min := MustParseAmount(tt.curr, tt.min) + max := MustParseAmount(tt.curr, tt.max) + got, err := a.Clamp(min, max) + if err != nil { + t.Errorf("%q.Clamp(%q, %q) failed: %v", a, min, max, err) + continue + } + want := MustParseAmount(tt.curr, tt.want) + if got != want { + t.Errorf("%q.Clamp(%q, %q) = %q, want %q", a, min, max, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + curra, a, currmin, min, currmax, max string + }{ + "invalid range 1": {"USD", "0", "USD", "1", "USD", "0"}, + "invalid range 2": {"USD", "0", "USD", "-1", "USD", "-2"}, + "currency 1": {"JPY", "0", "USD", "-1", "USD", "1"}, + "currency 2": {"USD", "0", "JPY", "-1", "USD", "1"}, + "currency 3": {"USD", "0", "USD", "-1", "JPY", "1"}, + } + for name, tt := range tests { + a := MustParseAmount(tt.curra, tt.a) + min := MustParseAmount(tt.currmin, tt.min) + max := MustParseAmount(tt.currmax, tt.max) + _, err := a.Clamp(min, max) + if err == nil { + t.Errorf("%s: %q.Clamp(%q, %q) did not fail", name, a, min, max) + } + } + }) +} + +func TestAmount_Rescale(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + curr, a string + scale int + want string + }{ + // Padding + {"JPY", "0", 0, "0"}, + {"JPY", "0", 1, "0.0"}, + {"JPY", "0", 2, "0.00"}, + {"JPY", "0", 3, "0.000"}, + {"USD", "0", 0, "0.00"}, + {"USD", "0", 1, "0.00"}, + {"USD", "0", 2, "0.00"}, + {"USD", "0", 3, "0.000"}, + {"OMR", "0", 0, "0.000"}, + {"OMR", "0", 1, "0.000"}, + {"OMR", "0", 2, "0.000"}, + {"OMR", "0", 3, "0.000"}, + {"USD", "0", 17, "0.00000000000000000"}, + {"USD", "0", 18, "0.000000000000000000"}, + {"USD", "0", 19, "0.0000000000000000000"}, + {"USD", "1", 17, "1.00000000000000000"}, + {"USD", "1", 18, "1.000000000000000000"}, + + // Half-to-even rounding + {"USD", "0.0049", 2, "0.00"}, + {"USD", "0.0051", 2, "0.01"}, + {"USD", "0.0149", 2, "0.01"}, + {"USD", "0.0151", 2, "0.02"}, + {"USD", "-0.0049", 2, "0.00"}, + {"USD", "-0.0051", 2, "-0.01"}, + {"USD", "-0.0149", 2, "-0.01"}, + {"USD", "-0.0151", 2, "-0.02"}, + {"USD", "0.0050", 2, "0.00"}, + {"USD", "0.0150", 2, "0.02"}, + {"USD", "0.0250", 2, "0.02"}, + {"USD", "0.0350", 2, "0.04"}, + {"USD", "-0.0050", 2, "0.00"}, + {"USD", "-0.0150", 2, "-0.02"}, + {"USD", "-0.0250", 2, "-0.02"}, + {"USD", "-0.0350", 2, "-0.04"}, + {"USD", "3.0448", 2, "3.04"}, + {"USD", "3.0450", 2, "3.04"}, + {"USD", "3.0452", 2, "3.05"}, + {"USD", "3.0956", 2, "3.10"}, + } + for _, tt := range tests { + a := MustParseAmount(tt.curr, tt.a) + got, err := a.Rescale(tt.scale) + if err != nil { + t.Errorf("%q.Rescale(%v) failed: %v", a, tt.scale, err) + continue + } + want := MustParseAmount(tt.curr, tt.want) + if got != want { + t.Errorf("%q.Rescale(%v) = %q, want %q", a, tt.scale, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + curr, a string + scale int + }{ + "overflow 1": {"JPY", "9999999999999999999", 1}, + "overflow 2": {"USD", "99999999999999999.99", 3}, + "overflow 3": {"OMR", "9999999999999999.999", 4}, + "overflow 4": {"USD", "0", 20}, + "overflow 5": {"USD", "1", 19}, + } + for _, tt := range tests { + a := MustParseAmount(tt.curr, tt.a) + _, err := a.Rescale(tt.scale) + if err == nil { + t.Errorf("%q.Rescale(%v) did not fail", a, tt.scale) + } + } + }) +} + +func TestAmount_Quantize(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + curr, a, b, want string + }{ + // Padding + {"JPY", "0", "0", "0"}, + {"JPY", "0", "0.0", "0.0"}, + {"JPY", "0", "0.00", "0.00"}, + {"JPY", "0", "0.000", "0.000"}, + {"USD", "0", "0", "0.00"}, + {"USD", "0", "0.0", "0.00"}, + {"USD", "0", "0.00", "0.00"}, + {"USD", "0", "0.000", "0.000"}, + {"OMR", "0", "0", "0.000"}, + {"OMR", "0", "0.0", "0.000"}, + {"OMR", "0", "0.00", "0.000"}, + {"OMR", "0", "0.000", "0.000"}, + {"USD", "0", "0.00000000000000000", "0.00000000000000000"}, + {"USD", "0", "0.000000000000000000", "0.000000000000000000"}, + {"USD", "0", "0.0000000000000000000", "0.0000000000000000000"}, + {"USD", "1", "0.00000000000000000", "1.00000000000000000"}, + {"USD", "1", "0.000000000000000000", "1.000000000000000000"}, + + // Half-to-even rounding + {"USD", "0.0049", "0.00", "0.00"}, + {"USD", "0.0051", "0.00", "0.01"}, + {"USD", "0.0149", "0.00", "0.01"}, + {"USD", "0.0151", "0.00", "0.02"}, + {"USD", "-0.0049", "0.00", "0.00"}, + {"USD", "-0.0051", "0.00", "-0.01"}, + {"USD", "-0.0149", "0.00", "-0.01"}, + {"USD", "-0.0151", "0.00", "-0.02"}, + {"USD", "0.0050", "0.00", "0.00"}, + {"USD", "0.0150", "0.00", "0.02"}, + {"USD", "0.0250", "0.00", "0.02"}, + {"USD", "0.0350", "0.00", "0.04"}, + {"USD", "-0.0050", "0.00", "0.00"}, + {"USD", "-0.0150", "0.00", "-0.02"}, + {"USD", "-0.0250", "0.00", "-0.02"}, + {"USD", "-0.0350", "0.00", "-0.04"}, + {"USD", "3.0448", "0.00", "3.04"}, + {"USD", "3.0450", "0.00", "3.04"}, + {"USD", "3.0452", "0.00", "3.05"}, + {"USD", "3.0956", "0.00", "3.10"}, + } + for _, tt := range tests { + a := MustParseAmount(tt.curr, tt.a) + b := MustParseAmount(tt.curr, tt.b) + got, err := a.Quantize(b) + if err != nil { + t.Errorf("%q.Quantize(%q) failed: %v", a, b, err) + continue + } + want := MustParseAmount(tt.curr, tt.want) + if got != want { + t.Errorf("%q.Quantize(%q) = %q, want %q", a, b, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + curr, a, b string + }{ + "overflow 1": {"JPY", "9999999999999999999", "0.1"}, + "overflow 2": {"USD", "99999999999999999.99", "0.001"}, + "overflow 3": {"OMR", "9999999999999999.999", "0.0001"}, + "overflow 4": {"USD", "1", "0.0000000000000000000"}, + } + for _, tt := range tests { + a := MustParseAmount(tt.curr, tt.a) + b := MustParseAmount(tt.curr, tt.b) + _, err := a.Quantize(b) + if err == nil { + t.Errorf("%q.Quantize(%q) did not fail", a, b) + } + } + }) +} diff --git a/currency.go b/currency.go index b602349..828e609 100644 --- a/currency.go +++ b/currency.go @@ -57,7 +57,7 @@ func MustParseCurr(curr string) Currency { // // [ratio]: https://en.wikipedia.org/wiki/ISO_4217#Minor_unit_fractions func (c Currency) Scale() int { - return scaleLookup[c] + return int(scaleLookup[c]) } // Num returns the [3-digit code] assigned to the currency by the ISO 4217 standard. @@ -127,15 +127,16 @@ func (c Currency) Value() (driver.Value, error) { } // Format implements the [fmt.Formatter] interface. -// The following [verbs] are available: +// The following [format verbs] are available: // -// %s, %v: USD -// %q: "USD" -// %c: USD +// | Verb | Example | Description | +// | ---------- | ------- | --------------- | +// | %c, %s, %v | USD | Currency | +// | %q | "USD" | Quoted currency | // // The '-' format flag can be used with all verbs. // -// [verbs]: https://pkg.go.dev/fmt#hdr-Printing +// [format verbs]: https://pkg.go.dev/fmt#hdr-Printing // [fmt.Formatter]: https://pkg.go.dev/fmt#Formatter func (c Currency) Format(state fmt.State, verb rune) { // Currency symbols @@ -206,3 +207,42 @@ func (c Currency) Format(state fmt.State, verb rune) { state.Write([]byte(")")) } } + +// NullCurrency represents a currency that can be null. +// Its zero value is null. +// NullCurrency is not thread-safe. +type NullCurrency struct { + Currency Currency + Valid bool +} + +// Scan implements the [sql.Scanner] interface. +// See also method [ParseCurr]. +// +// [sql.Scanner]: https://pkg.go.dev/database/sql#Scanner +func (n *NullCurrency) Scan(value any) error { + if value == nil { + n.Currency = XXX + n.Valid = false + return nil + } + err := n.Currency.Scan(value) + if err != nil { + n.Currency = XXX + n.Valid = false + return err + } + n.Valid = true + return nil +} + +// Value implements the [driver.Valuer] interface. +// See also method [Currency.String]. +// +// [driver.Valuer]: https://pkg.go.dev/database/sql/driver#Valuer +func (n NullCurrency) Value() (driver.Value, error) { + if !n.Valid { + return nil, nil + } + return n.Currency.Value() +} diff --git a/currency_data.go b/currency_data.go index a7f9bd7..6b28451 100644 --- a/currency_data.go +++ b/currency_data.go @@ -325,7 +325,7 @@ var currLookup = map[string]Currency{ "ZWL": ZWL, "zwl": ZWL, "932": ZWL, // Zimbabwe Dollar } -var scaleLookup = [...]int{ +var scaleLookup = [...]int8{ 0, // No Currency 2, // Test Currency 2, // U.A.E. Dirham diff --git a/doc_test.go b/doc_test.go index d7d3420..20d0474 100644 --- a/doc_test.go +++ b/doc_test.go @@ -1,55 +1,57 @@ package money_test import ( + "encoding/json" "fmt" "strconv" + "strings" "github.com/govalues/decimal" "github.com/govalues/money" ) -func TaxAmount(priceAfterTax money.Amount, taxRate decimal.Decimal) (money.Amount, money.Amount, error) { - // Price +func TaxAmount(price money.Amount, taxRate decimal.Decimal) (money.Amount, money.Amount, error) { + // Subtotal one := taxRate.One() taxRate, err := taxRate.Add(one) if err != nil { return money.Amount{}, money.Amount{}, err } - - priceBeforeTax, err := priceAfterTax.Quo(taxRate) + subtotal, err := price.Quo(taxRate) if err != nil { return money.Amount{}, money.Amount{}, err } - priceBeforeTax = priceBeforeTax.RoundToCurr() + + // Function depends on the locax tax laws + subtotal = subtotal.TruncToCurr() // Tax Amount - taxAmount, err := priceAfterTax.Sub(priceBeforeTax) + tax, err := price.Sub(subtotal) if err != nil { return money.Amount{}, money.Amount{}, err } - return priceBeforeTax, taxAmount, nil + return subtotal, tax, nil } // In this example, the sales tax amount is calculated for a product with // a given price after tax, using a specified tax rate. func Example_taxCalculation() { - priceAfterTax := money.MustParseAmount("USD", "10") - vatRate := decimal.MustParse("0.065") + price := money.MustParseAmount("USD", "9.99") + taxRate := decimal.MustParse("0.0725") - priceBeforeTax, vatAmount, err := TaxAmount(priceAfterTax, vatRate) + subtotal, tax, err := TaxAmount(price, taxRate) if err != nil { panic(err) } - fmt.Printf("Price (before tax) = %v\n", priceBeforeTax) - fmt.Printf("VAT %-6k = %v\n", vatRate, vatAmount) - fmt.Printf("Price (after tax) = %v\n", priceAfterTax) - + fmt.Printf("Subtotal = %v\n", subtotal) + fmt.Printf("Sales tax %-6k = %v\n", taxRate, tax) + fmt.Printf("Total price = %v\n", price) // Output: - // Price (before tax) = USD 9.39 - // VAT 6.5% = USD 0.61 - // Price (after tax) = USD 10.00 + // Subtotal = USD 9.31 + // Sales tax 7.25% = USD 0.68 + // Total price = USD 9.99 } type StatementLine struct { @@ -89,7 +91,7 @@ func (s Statement) OutgoingBalance() (money.Amount, error) { return s[len(s)-1].Balance, nil } -// PercChange method calculates (OutgoingBalance - IncomingBalance) / IncomingBalance. +// PercChange computes (OutgoingBalance - IncomingBalance) / IncomingBalance. func (s Statement) PercChange() (decimal.Decimal, error) { inc, err := s.IncomingBalance() if err != nil { @@ -125,11 +127,20 @@ func (s Statement) TotalInterest() (money.Amount, error) { return total, nil } +// DailyRate computes YearlyRate / 365. func DailyRate(yearlyRate decimal.Decimal) (decimal.Decimal, error) { - daysInYear := decimal.MustNew(365, 0) - return yearlyRate.Quo(daysInYear) + daysInYear, err := decimal.New(365, 0) + if err != nil { + return decimal.Decimal{}, err + } + dailyRate, err := yearlyRate.Quo(daysInYear) + if err != nil { + return decimal.Decimal{}, err + } + return dailyRate, nil } +// MonthlyInterest computes Balance * DailyRate * DaysInMonth. func MonthlyInterest(balance money.Amount, dailyRate decimal.Decimal, daysInMonth int) (money.Amount, error) { var err error interest := balance.Zero() @@ -139,7 +150,8 @@ func MonthlyInterest(balance money.Amount, dailyRate decimal.Decimal, daysInMont return money.Amount{}, err } } - return interest.RoundToCurr(), nil + interest = interest.RoundToCurr() + return interest, nil } func SimulateStatement(balance money.Amount, yearlyRate decimal.Decimal) (Statement, error) { @@ -176,7 +188,6 @@ func Example_effectiveRate() { // Display initial balance and nominal interest rate fmt.Printf("Initial Balance = %v\n", initialBalance) fmt.Printf("Nominal Rate = %.2k\n\n", nominalRate) - fmt.Printf("Month Days Interest Balance\n") // Generate the simulated statement for a year statement, err := SimulateStatement(initialBalance, nominalRate) @@ -185,6 +196,7 @@ func Example_effectiveRate() { } // Display monthly balances, including the interest accrued each month + fmt.Printf("%-5s %-5s %-12s %s\n", "Month", "Days", "Interest", "Balance") for _, line := range statement { fmt.Printf("%5v %5v %+11f %11f\n", line.Month, line.Days, line.Interest, line.Balance) } @@ -291,12 +303,20 @@ func (p AmortizationSchedule) TotalInterest() (money.Amount, error) { return total, nil } +// MonthlyRate computes YearlyRate / 12. func MonthlyRate(yearlyRate decimal.Decimal) (decimal.Decimal, error) { - monthsInYear := decimal.MustNew(12, 0) - return yearlyRate.Quo(monthsInYear) + monthsInYear, err := decimal.New(12, 0) + if err != nil { + return decimal.Decimal{}, err + } + monthlyRate, err := yearlyRate.Quo(monthsInYear) + if err != nil { + return decimal.Decimal{}, err + } + return monthlyRate, nil } -// AnnuityPayment function calculates Amount * Rate / (1 - (1 + Rate)^(-Periods)). +// AnnuityPayment computes Amount * Rate / (1 - (1 + Rate)^(-Periods)). func AnnuityPayment(amount money.Amount, rate decimal.Decimal, periods int) (money.Amount, error) { one := rate.One() // Numerator @@ -360,13 +380,12 @@ func SimulateSchedule(balance money.Amount, yearlyRate decimal.Decimal, years in func Example_loanAmortization() { // Set up initial loan balance and interest rate initialBalance := money.MustParseAmount("USD", "12000") - yearlyRate := decimal.MustParse("0.1") + yearlyRate := decimal.MustParse("0.10") years := 1 // Display the initial loan balance and interest rate fmt.Printf("Initial Balance = %v\n", initialBalance) fmt.Printf("Interest Rate = %.2k\n\n", yearlyRate) - fmt.Println("Month Repayment Principal Interest Outstanding") // Generate the amortization schedule schedule, err := SimulateSchedule(initialBalance, yearlyRate, years) @@ -376,6 +395,7 @@ func Example_loanAmortization() { // Display the amortization schedule, showing the monthly // repayment, principal, interest and outstanding loan balance + fmt.Println("Month Repayment Principal Interest Outstanding") for _, line := range schedule { fmt.Printf("%5d %12f %11f %11f %11f\n", line.Month, line.Repayment, line.Principal, line.Interest, line.Balance) } @@ -417,443 +437,828 @@ func Example_loanAmortization() { // Total 12659.88 11999.98 659.90 } -func ParseISO8583(s string) (money.Amount, error) { - // Currency - c, err := money.ParseCurr(s[:3]) - if err != nil { - return money.Amount{}, err - } +func FromISO8583(s string) (money.Amount, error) { // Amount n, err := strconv.ParseInt(s[4:], 10, 64) if err != nil { return money.Amount{}, err } - d, err := decimal.New(n, c.Scale()) + a, err := money.NewAmountFromMinorUnits(s[:3], n) if err != nil { return money.Amount{}, err } // Sign if s[3:4] == "D" { - d = d.Neg() + a = a.Neg() } - return money.NewAmount(c, d) + return a, nil } // In this example, we parse the string "840D000000001234", which represents -12.34 USD, // according to the specification for "DE54, Additional Amounts" in ISO 8583. func Example_parsingISO8583() { - a, err := ParseISO8583("840D000000001234") - if err != nil { - panic(err) - } + a, _ := FromISO8583("840D000000001234") fmt.Println(a) - // Output: USD -12.34 + // Output: + // USD -12.34 } -func ParseMoneyProto(curr string, units int64, nanos int32) (money.Amount, error) { - // Currency - c, err := money.ParseCurr(curr) - if err != nil { - return money.Amount{}, err - } - // Amount - d, err := decimal.NewFromInt64(units, int64(nanos), 9) - if err != nil { - return money.Amount{}, err - } - d = d.Trim(c.Scale()) - return money.NewAmount(c, d) +func FromMoneyProto(curr string, units int64, nanos int32) (money.Amount, error) { + return money.NewAmountFromInt64(curr, units, int64(nanos), 9) } -// This is an example of how to a parse a monetary amount formatted as [MoneyProto]. +func ToMoneyProto(a money.Amount) (curr string, units int64, nanos int32, ok bool) { + curr = a.Curr().Code() + whole, frac, ok := a.Int64(9) + return curr, whole, int32(frac), ok +} + +// This is an example of how to a parse a monetary amount formatted as [money.proto]. // -// [MoneyProto]: https://github.com/googleapis/googleapis/blob/master/google/type/money.proto +// [money.proto]: https://github.com/googleapis/googleapis/blob/master/google/type/money.proto func Example_parsingProtobuf() { - a, err := ParseMoneyProto("840", -12, -340000000) - if err != nil { - panic(err) - } + a, _ := FromMoneyProto("USD", 5, 670000000) fmt.Println(a) - // Output: USD -12.34 + fmt.Println(ToMoneyProto(a)) + // Output: + // USD 5.67 + // USD 5 670000000 true } -func ParseStripe(currency string, amount int64) (money.Amount, error) { - // Currency - c, err := money.ParseCurr(currency) - if err != nil { - return money.Amount{}, err - } - // Amount - d, err := decimal.New(amount, c.Scale()) - if err != nil { - return money.Amount{}, err - } - return money.NewAmount(c, d) +func FromStripe(curr string, units int64) (money.Amount, error) { + return money.NewAmountFromMinorUnits(curr, units) +} + +func ToStripe(a money.Amount) (curr string, units int64, ok bool) { + curr = strings.ToLower(a.Curr().Code()) + units, ok = a.MinorUnits() + return curr, units, ok } // This is an example of how to a parse a monetary amount -// formatted according to Stripe API specification. +// formatted according to [Stripe API] specification. +// +// [Stripe API]: https://stripe.com/docs/api/balance/balance_object func Example_parsingStripe() { - a, err := ParseStripe("usd", -1234) - if err != nil { - panic(err) - } + a, _ := FromStripe("usd", 567) fmt.Println(a) - // Output: USD -12.34 + fmt.Println(ToStripe(a)) + // Output: + // USD 5.67 + // usd 567 true } -func ExampleMustNewAmount() { - c := money.USD - d := decimal.MustNew(12345, 2) - a := money.MustNewAmount(c, d) - fmt.Println(a) - // Output: USD 123.45 +func ExampleParseCurr_currencies() { + fmt.Println(money.ParseCurr("JPY")) + fmt.Println(money.ParseCurr("USD")) + fmt.Println(money.ParseCurr("OMR")) + // Output: + // JPY + // USD + // OMR +} + +func ExampleParseCurr_codes() { + fmt.Println(money.ParseCurr("usd")) + fmt.Println(money.ParseCurr("USD")) + fmt.Println(money.ParseCurr("840")) + // Output: + // USD + // USD + // USD +} + +func ExampleMustParseCurr_currencies() { + fmt.Println(money.MustParseCurr("JPY")) + fmt.Println(money.MustParseCurr("USD")) + fmt.Println(money.MustParseCurr("OMR")) + // Output: + // JPY + // USD + // OMR } -func ExampleNewAmount() { +func ExampleMustParseCurr_codes() { + fmt.Println(money.MustParseCurr("usd")) + fmt.Println(money.MustParseCurr("USD")) + fmt.Println(money.MustParseCurr("840")) + // Output: + // USD + // USD + // USD +} + +func ExampleCurrency_String() { c := money.USD - d := decimal.MustNew(12345, 2) - fmt.Println(money.NewAmount(c, d)) - // Output: USD 123.45 + fmt.Println(c.String()) + // Output: USD } -func ExampleMustParseAmount() { - fmt.Println(money.MustParseAmount("USD", "-1.2")) - // Output: USD -1.20 +func ExampleCurrency_Code() { + j := money.JPY + u := money.USD + o := money.OMR + fmt.Println(j.Code()) + fmt.Println(u.Code()) + fmt.Println(o.Code()) + // Output: + // JPY + // USD + // OMR } -func ExampleParseAmount() { - fmt.Println(money.ParseAmount("USD", "-12.3")) - // Output: USD -12.30 +func ExampleCurrency_Num() { + j := money.JPY + u := money.USD + o := money.OMR + fmt.Println(j.Num()) + fmt.Println(u.Num()) + fmt.Println(o.Num()) + // Output: + // 392 + // 840 + // 512 } -func ExampleAmount_Coef() { - a := money.MustParseAmount("JPY", "-123") - b := money.MustParseAmount("JPY", "5.7") - c := money.MustParseAmount("JPY", "0.4") - fmt.Println(a.Coef()) - fmt.Println(b.Coef()) - fmt.Println(c.Coef()) +func ExampleCurrency_Scale() { + j := money.JPY + u := money.USD + o := money.OMR + fmt.Println(j.Scale()) + fmt.Println(u.Scale()) + fmt.Println(o.Scale()) // Output: - // 123 - // 57 - // 4 + // 0 + // 2 + // 3 +} + +type Value struct { + Currency money.Currency `json:"currency"` +} + +func ExampleCurrency_UnmarshalText() { + var v Value + _ = json.Unmarshal([]byte(`{"currency":"USD"}`), &v) + fmt.Println(v) + // Output: {USD} +} + +func ExampleCurrency_MarshalText() { + v := Value{ + Currency: money.USD, + } + b, _ := json.Marshal(v) + fmt.Println(string(b)) + // Output: {"currency":"USD"} +} + +func ExampleCurrency_Scan() { + u := money.XXX + _ = u.Scan("USD") + fmt.Println(u) + // Output: USD +} + +func ExampleCurrency_Value() { + u := money.USD + fmt.Println(u.Value()) + // Output: USD +} + +func ExampleCurrency_Format() { + fmt.Printf("%c\n", money.USD) + // Output: + // USD +} + +func ExampleNullCurrency_Scan() { + var n, m money.NullCurrency + _ = n.Scan("USD") + _ = m.Scan(nil) + fmt.Println(n) + fmt.Println(m) + // Output: + // {USD true} + // {XXX false} +} + +func ExampleNullCurrency_Value() { + n := money.NullCurrency{ + Currency: money.USD, + Valid: true, + } + m := money.NullCurrency{ + Currency: money.XXX, + Valid: false, + } + fmt.Println(n.Value()) + fmt.Println(m.Value()) + // Output: + // USD + // +} + +func ExampleNewAmount_scales() { + fmt.Println(money.NewAmount("USD", 567, 0)) + fmt.Println(money.NewAmount("USD", 567, 1)) + fmt.Println(money.NewAmount("USD", 567, 2)) + fmt.Println(money.NewAmount("USD", 567, 3)) + fmt.Println(money.NewAmount("USD", 567, 4)) + // Output: + // USD 567.00 + // USD 56.70 + // USD 5.67 + // USD 0.567 + // USD 0.0567 +} + +func ExampleNewAmount_currencies() { + fmt.Println(money.NewAmount("JPY", 567, 2)) + fmt.Println(money.NewAmount("USD", 567, 2)) + fmt.Println(money.NewAmount("OMR", 567, 2)) + // Output: + // JPY 5.67 + // USD 5.67 + // OMR 5.670 +} + +func ExampleMustNewAmount_scales() { + fmt.Println(money.MustNewAmount("USD", 567, 0)) + fmt.Println(money.MustNewAmount("USD", 567, 1)) + fmt.Println(money.MustNewAmount("USD", 567, 2)) + fmt.Println(money.MustNewAmount("USD", 567, 3)) + fmt.Println(money.MustNewAmount("USD", 567, 4)) + // Output: + // USD 567.00 + // USD 56.70 + // USD 5.67 + // USD 0.567 + // USD 0.0567 +} + +func ExampleMustNewAmount_currencies() { + fmt.Println(money.MustNewAmount("JPY", 567, 2)) + fmt.Println(money.MustNewAmount("USD", 567, 2)) + fmt.Println(money.MustNewAmount("OMR", 567, 2)) + // Output: + // JPY 5.67 + // USD 5.67 + // OMR 5.670 +} + +func ExampleNewAmountFromDecimal() { + d := decimal.MustParse("5.67") + fmt.Println(money.NewAmountFromDecimal(money.JPY, d)) + fmt.Println(money.NewAmountFromDecimal(money.USD, d)) + fmt.Println(money.NewAmountFromDecimal(money.OMR, d)) + // Output: + // JPY 5.67 + // USD 5.67 + // OMR 5.670 +} + +func ExampleNewAmountFromInt64_scales() { + fmt.Println(money.NewAmountFromInt64("USD", 5, 67, 2)) + fmt.Println(money.NewAmountFromInt64("USD", 5, 67, 3)) + fmt.Println(money.NewAmountFromInt64("USD", 5, 67, 4)) + fmt.Println(money.NewAmountFromInt64("USD", 5, 67, 5)) + fmt.Println(money.NewAmountFromInt64("USD", 5, 67, 6)) + // Output: + // USD 5.67 + // USD 5.067 + // USD 5.0067 + // USD 5.00067 + // USD 5.000067 +} + +func ExampleNewAmountFromInt64_currencies() { + fmt.Println(money.NewAmountFromInt64("JPY", 5, 67, 2)) + fmt.Println(money.NewAmountFromInt64("USD", 5, 67, 2)) + fmt.Println(money.NewAmountFromInt64("OMR", 5, 67, 2)) + // Output: + // JPY 5.67 + // USD 5.67 + // OMR 5.670 } -func ExampleAmount_MinorUnits() { - a := money.MustParseAmount("JPY", "-1.6789") - b := money.MustParseAmount("USD", "-1.6789") - c := money.MustParseAmount("OMR", "-1.6789") +func ExampleNewAmountFromFloat64_currencies() { + fmt.Println(money.NewAmountFromFloat64("JPY", 5.67e0)) + fmt.Println(money.NewAmountFromFloat64("USD", 5.67e0)) + fmt.Println(money.NewAmountFromFloat64("OMR", 5.67e0)) + // Output: + // JPY 5.67 + // USD 5.67 + // OMR 5.670 +} + +func ExampleNewAmountFromFloat64_scales() { + fmt.Println(money.NewAmountFromFloat64("USD", 5.67e-2)) + fmt.Println(money.NewAmountFromFloat64("USD", 5.67e-1)) + fmt.Println(money.NewAmountFromFloat64("USD", 5.67e0)) + fmt.Println(money.NewAmountFromFloat64("USD", 5.67e1)) + fmt.Println(money.NewAmountFromFloat64("USD", 5.67e2)) + // Output: + // USD 0.0567 + // USD 0.567 + // USD 5.67 + // USD 56.70 + // USD 567.00 +} + +func ExampleNewAmountFromMinorUnits_currencies() { + fmt.Println(money.NewAmountFromMinorUnits("JPY", 567)) + fmt.Println(money.NewAmountFromMinorUnits("USD", 567)) + fmt.Println(money.NewAmountFromMinorUnits("OMR", 567)) + // Output: + // JPY 567 + // USD 5.67 + // OMR 0.567 +} + +func ExampleNewAmountFromMinorUnits_scales() { + fmt.Println(money.NewAmountFromMinorUnits("USD", 5)) + fmt.Println(money.NewAmountFromMinorUnits("USD", 56)) + fmt.Println(money.NewAmountFromMinorUnits("USD", 567)) + fmt.Println(money.NewAmountFromMinorUnits("USD", 5670)) + fmt.Println(money.NewAmountFromMinorUnits("USD", 56700)) + // Output: + // USD 0.05 + // USD 0.56 + // USD 5.67 + // USD 56.70 + // USD 567.00 +} + +func ExampleMustParseAmount_currencies() { + fmt.Println(money.MustParseAmount("JPY", "5.67")) + fmt.Println(money.MustParseAmount("USD", "5.67")) + fmt.Println(money.MustParseAmount("OMR", "5.67")) + // Output: + // JPY 5.67 + // USD 5.67 + // OMR 5.670 +} + +func ExampleMustParseAmount_scales() { + fmt.Println(money.MustParseAmount("USD", "0.0567")) + fmt.Println(money.MustParseAmount("USD", "0.567")) + fmt.Println(money.MustParseAmount("USD", "5.67")) + fmt.Println(money.MustParseAmount("USD", "56.7")) + fmt.Println(money.MustParseAmount("USD", "567")) + // Output: + // USD 0.0567 + // USD 0.567 + // USD 5.67 + // USD 56.70 + // USD 567.00 +} + +func ExampleParseAmount_currencies() { + fmt.Println(money.ParseAmount("JPY", "5.67")) + fmt.Println(money.ParseAmount("USD", "5.67")) + fmt.Println(money.ParseAmount("OMR", "5.67")) + // Output: + // JPY 5.67 + // USD 5.67 + // OMR 5.670 +} + +func ExampleParseAmount_scales() { + fmt.Println(money.ParseAmount("USD", "0.0567")) + fmt.Println(money.ParseAmount("USD", "0.567")) + fmt.Println(money.ParseAmount("USD", "5.67")) + fmt.Println(money.ParseAmount("USD", "56.7")) + fmt.Println(money.ParseAmount("USD", "567")) + // Output: + // USD 0.0567 + // USD 0.567 + // USD 5.67 + // USD 56.70 + // USD 567.00 +} + +func ExampleAmount_MinorUnits_currencies() { + a := money.MustParseAmount("JPY", "5.678") + b := money.MustParseAmount("USD", "5.678") + c := money.MustParseAmount("OMR", "5.678") fmt.Println(a.MinorUnits()) fmt.Println(b.MinorUnits()) fmt.Println(c.MinorUnits()) // Output: - // -2 true - // -168 true - // -1679 true + // 6 true + // 568 true + // 5678 true +} + +func ExampleAmount_MinorUnits_scales() { + a := money.MustParseAmount("USD", "0.0567") + b := money.MustParseAmount("USD", "0.567") + c := money.MustParseAmount("USD", "5.67") + d := money.MustParseAmount("USD", "56.7") + e := money.MustParseAmount("USD", "567") + fmt.Println(a.MinorUnits()) + fmt.Println(b.MinorUnits()) + fmt.Println(c.MinorUnits()) + fmt.Println(d.MinorUnits()) + fmt.Println(e.MinorUnits()) + // Output: + // 6 true + // 57 true + // 567 true + // 5670 true + // 56700 true } func ExampleAmount_Float64() { - a := money.MustParseAmount("JPY", "100") - b := money.MustParseAmount("USD", "15.6") - c := money.MustParseAmount("OMR", "2.389") + a := money.MustParseAmount("USD", "0.10") + b := money.MustParseAmount("USD", "123.456") + c := money.MustParseAmount("USD", "1234567890.123456789") fmt.Println(a.Float64()) fmt.Println(b.Float64()) fmt.Println(c.Float64()) // Output: - // 100 true - // 15.6 true - // 2.389 true + // 0.1 true + // 123.456 true + // 1.2345678901234567e+09 true } func ExampleAmount_Int64() { - a := money.MustParseAmount("USD", "15.67") - fmt.Println(a.Int64(5)) - fmt.Println(a.Int64(4)) - fmt.Println(a.Int64(3)) - fmt.Println(a.Int64(2)) - fmt.Println(a.Int64(1)) + a := money.MustParseAmount("USD", "5.678") fmt.Println(a.Int64(0)) + fmt.Println(a.Int64(1)) + fmt.Println(a.Int64(2)) + fmt.Println(a.Int64(3)) + fmt.Println(a.Int64(4)) // Output: - // 15 67000 true - // 15 6700 true - // 15 670 true - // 15 67 true - // 15 7 true - // 16 0 true -} - -func ExampleAmount_Prec() { - a := money.MustParseAmount("JPY", "-123") - b := money.MustParseAmount("JPY", "5.7") - c := money.MustParseAmount("JPY", "0.4") - fmt.Println(a.Prec()) - fmt.Println(b.Prec()) - fmt.Println(c.Prec()) - // Output: - // 3 - // 2 - // 1 + // 0 0 false + // 0 0 false + // 5 68 true + // 5 678 true + // 5 6780 true } func ExampleAmount_Curr() { - a := money.MustParseAmount("USD", "15.6") + a := money.MustParseAmount("USD", "5.67") fmt.Println(a.Curr()) // Output: USD } +func ExampleAmount_Decimal() { + a := money.MustParseAmount("USD", "5.67") + fmt.Println(a.Decimal()) + // Output: 5.67 +} + func ExampleAmount_Add() { - a := money.MustParseAmount("USD", "15.6") - b := money.MustParseAmount("USD", "8") + a := money.MustParseAmount("USD", "5.67") + b := money.MustParseAmount("USD", "23.00") fmt.Println(a.Add(b)) - // Output: USD 23.60 + // Output: USD 28.67 } func ExampleAmount_Sub() { - a := money.MustParseAmount("USD", "15.6") - b := money.MustParseAmount("USD", "8") + a := money.MustParseAmount("USD", "5.67") + b := money.MustParseAmount("USD", "23.00") fmt.Println(a.Sub(b)) - // Output: USD 7.60 + // Output: USD -17.33 +} + +func ExampleAmount_SubAbs() { + a := money.MustParseAmount("USD", "5.67") + b := money.MustParseAmount("USD", "23.00") + fmt.Println(a.SubAbs(b)) + // Output: USD 17.33 } func ExampleAmount_FMA() { - a := money.MustParseAmount("USD", "2") - b := money.MustParseAmount("USD", "4") - e := decimal.MustParse("3") + a := money.MustParseAmount("USD", "5.67") + b := money.MustParseAmount("USD", "23.00") + e := decimal.MustParse("2") fmt.Println(a.FMA(e, b)) - // Output: USD 10.00 + // Output: USD 34.34 } func ExampleAmount_Mul() { - a := money.MustParseAmount("USD", "5.7") - e := decimal.MustParse("3") + a := money.MustParseAmount("USD", "5.67") + e := decimal.MustParse("2") fmt.Println(a.Mul(e)) - // Output: USD 17.10 + // Output: USD 11.34 } func ExampleAmount_Quo() { - a := money.MustParseAmount("USD", "-15.67") + a := money.MustParseAmount("USD", "5.67") e := decimal.MustParse("2") fmt.Println(a.Quo(e)) - // Output: USD -7.835 + // Output: USD 2.835 } func ExampleAmount_QuoRem() { - a := money.MustParseAmount("USD", "-15.67") + a := money.MustParseAmount("JPY", "5.67") + b := money.MustParseAmount("USD", "5.67") + c := money.MustParseAmount("OMR", "5.67") e := decimal.MustParse("2") fmt.Println(a.QuoRem(e)) - // Output: USD -7.83 USD -0.01 + fmt.Println(b.QuoRem(e)) + fmt.Println(c.QuoRem(e)) + // Output: + // JPY 2 JPY 1.67 + // USD 2.83 USD 0.01 + // OMR 2.835 OMR 0.000 } -func ExampleAmount_Split() { - a := money.MustParseAmount("USD", "1.01") - fmt.Println(a.Split(5)) - fmt.Println(a.Split(4)) - fmt.Println(a.Split(3)) +func ExampleAmount_Split_scales() { + a := money.MustParseAmount("USD", "0.0567") + b := money.MustParseAmount("USD", "0.567") + c := money.MustParseAmount("USD", "5.67") + d := money.MustParseAmount("USD", "56.7") + e := money.MustParseAmount("USD", "567") fmt.Println(a.Split(2)) + fmt.Println(b.Split(2)) + fmt.Println(c.Split(2)) + fmt.Println(d.Split(2)) + fmt.Println(e.Split(2)) + // Output: + // [USD 0.0284 USD 0.0283] + // [USD 0.284 USD 0.283] + // [USD 2.84 USD 2.83] + // [USD 28.35 USD 28.35] + // [USD 283.50 USD 283.50] +} + +func ExampleAmount_Split_parts() { + a := money.MustParseAmount("USD", "5.67") fmt.Println(a.Split(1)) + fmt.Println(a.Split(2)) + fmt.Println(a.Split(3)) + fmt.Println(a.Split(4)) + fmt.Println(a.Split(5)) // Output: - // [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] + // [USD 5.67] + // [USD 2.84 USD 2.83] + // [USD 1.89 USD 1.89 USD 1.89] + // [USD 1.42 USD 1.42 USD 1.42 USD 1.41] + // [USD 1.14 USD 1.14 USD 1.13 USD 1.13 USD 1.13] } func ExampleAmount_Rat() { - a := money.MustParseAmount("USD", "8") + a := money.MustParseAmount("EUR", "8") b := money.MustParseAmount("USD", "10") fmt.Println(a.Rat(b)) // Output: 0.8 } -func ExampleAmount_Rescale() { - a := money.MustParseAmount("USD", "15.6789") - fmt.Println(a.Rescale(6)) - fmt.Println(a.Rescale(5)) - fmt.Println(a.Rescale(4)) - fmt.Println(a.Rescale(3)) - fmt.Println(a.Rescale(2)) - fmt.Println(a.Rescale(1)) +func ExampleAmount_Rescale_currencies() { + a := money.MustParseAmount("JPY", "5.678") + b := money.MustParseAmount("USD", "5.678") + c := money.MustParseAmount("OMR", "5.678") fmt.Println(a.Rescale(0)) + fmt.Println(b.Rescale(0)) + fmt.Println(c.Rescale(0)) // Output: - // USD 15.678900 - // USD 15.67890 - // USD 15.6789 - // USD 15.679 - // USD 15.68 - // USD 15.68 - // USD 15.68 + // JPY 6 + // USD 5.68 + // OMR 5.678 } -func ExampleAmount_Round() { - a := money.MustParseAmount("USD", "15.6789") - fmt.Println(a.Round(5)) - fmt.Println(a.Round(4)) - fmt.Println(a.Round(3)) - fmt.Println(a.Round(2)) - fmt.Println(a.Round(1)) +func ExampleAmount_Rescale_scales() { + a := money.MustParseAmount("USD", "5.6789") + fmt.Println(a.Rescale(0)) + fmt.Println(a.Rescale(1)) + fmt.Println(a.Rescale(2)) + fmt.Println(a.Rescale(3)) + fmt.Println(a.Rescale(4)) + // Output: + // USD 5.68 + // USD 5.68 + // USD 5.68 + // USD 5.679 + // USD 5.6789 +} + +func ExampleAmount_Round_currencies() { + a := money.MustParseAmount("JPY", "5.678") + b := money.MustParseAmount("USD", "5.678") + c := money.MustParseAmount("OMR", "5.678") + fmt.Println(a.Round(0)) + fmt.Println(b.Round(0)) + fmt.Println(c.Round(0)) + // Output: + // JPY 6 + // USD 5.68 + // OMR 5.678 +} + +func ExampleAmount_Round_scales() { + a := money.MustParseAmount("USD", "5.6789") fmt.Println(a.Round(0)) + fmt.Println(a.Round(1)) + fmt.Println(a.Round(2)) + fmt.Println(a.Round(3)) + fmt.Println(a.Round(4)) // Output: - // USD 15.6789 - // USD 15.6789 - // USD 15.679 - // USD 15.68 - // USD 15.68 - // USD 15.68 + // USD 5.68 + // USD 5.68 + // USD 5.68 + // USD 5.679 + // USD 5.6789 } func ExampleAmount_RoundToCurr() { - a := money.MustParseAmount("JPY", "1.5678") - b := money.MustParseAmount("USD", "1.5678") - c := money.MustParseAmount("OMR", "1.5678") + a := money.MustParseAmount("JPY", "5.678") + b := money.MustParseAmount("USD", "5.678") + c := money.MustParseAmount("OMR", "5.678") fmt.Println(a.RoundToCurr()) fmt.Println(b.RoundToCurr()) fmt.Println(c.RoundToCurr()) // Output: - // JPY 2 - // USD 1.57 - // OMR 1.568 + // JPY 6 + // USD 5.68 + // OMR 5.678 } func ExampleAmount_Quantize() { - a := money.MustParseAmount("JPY", "15.6789") - x := money.MustParseAmount("JPY", "0.01") + a := money.MustParseAmount("JPY", "5.678") + x := money.MustParseAmount("JPY", "1") y := money.MustParseAmount("JPY", "0.1") - z := money.MustParseAmount("JPY", "1") + z := money.MustParseAmount("JPY", "0.01") fmt.Println(a.Quantize(x)) fmt.Println(a.Quantize(y)) fmt.Println(a.Quantize(z)) // Output: - // JPY 15.68 - // JPY 15.7 - // JPY 16 + // JPY 6 + // JPY 5.7 + // JPY 5.68 } -func ExampleAmount_Ceil() { - a := money.MustParseAmount("USD", "15.6789") - fmt.Println(a.Ceil(5)) - fmt.Println(a.Ceil(4)) - fmt.Println(a.Ceil(3)) - fmt.Println(a.Ceil(2)) - fmt.Println(a.Ceil(1)) +func ExampleAmount_Ceil_currencies() { + a := money.MustParseAmount("JPY", "5.678") + b := money.MustParseAmount("USD", "5.678") + c := money.MustParseAmount("OMR", "5.678") fmt.Println(a.Ceil(0)) + fmt.Println(b.Ceil(0)) + fmt.Println(c.Ceil(0)) // Output: - // USD 15.6789 - // USD 15.6789 - // USD 15.679 - // USD 15.68 - // USD 15.68 - // USD 15.68 -} - -func ExampleAmount_CeilToCurr() { - a := money.MustParseAmount("JPY", "1.5678") - b := money.MustParseAmount("USD", "1.5678") - c := money.MustParseAmount("OMR", "1.5678") - fmt.Println(a.CeilToCurr()) - fmt.Println(b.CeilToCurr()) - fmt.Println(c.CeilToCurr()) - // Output: - // JPY 2 - // USD 1.57 - // OMR 1.568 + // JPY 6 + // USD 5.68 + // OMR 5.678 } -func ExampleAmount_Floor() { - a := money.MustParseAmount("USD", "15.6789") - fmt.Println(a.Floor(5)) - fmt.Println(a.Floor(4)) - fmt.Println(a.Floor(3)) - fmt.Println(a.Floor(2)) - fmt.Println(a.Floor(1)) +func ExampleAmount_Ceil_scales() { + a := money.MustParseAmount("USD", "5.6789") + fmt.Println(a.Ceil(0)) + fmt.Println(a.Ceil(1)) + fmt.Println(a.Ceil(2)) + fmt.Println(a.Ceil(3)) + fmt.Println(a.Ceil(4)) + // Output: + // USD 5.68 + // USD 5.68 + // USD 5.68 + // USD 5.679 + // USD 5.6789 +} + +func ExampleAmount_CeilToCurr() { + a := money.MustParseAmount("JPY", "5.678") + b := money.MustParseAmount("USD", "5.678") + c := money.MustParseAmount("OMR", "5.678") + fmt.Println(a.CeilToCurr()) + fmt.Println(b.CeilToCurr()) + fmt.Println(c.CeilToCurr()) + // Output: + // JPY 6 + // USD 5.68 + // OMR 5.678 +} + +func ExampleAmount_Floor_currencies() { + a := money.MustParseAmount("JPY", "5.678") + b := money.MustParseAmount("USD", "5.678") + c := money.MustParseAmount("OMR", "5.678") fmt.Println(a.Floor(0)) + fmt.Println(b.Floor(0)) + fmt.Println(c.Floor(0)) // Output: - // USD 15.6789 - // USD 15.6789 - // USD 15.678 - // USD 15.67 - // USD 15.67 - // USD 15.67 + // JPY 5 + // USD 5.67 + // OMR 5.678 +} + +func ExampleAmount_Floor_scales() { + a := money.MustParseAmount("USD", "5.6789") + fmt.Println(a.Floor(0)) + fmt.Println(a.Floor(1)) + fmt.Println(a.Floor(2)) + fmt.Println(a.Floor(3)) + fmt.Println(a.Floor(4)) + // Output: + // USD 5.67 + // USD 5.67 + // USD 5.67 + // USD 5.678 + // USD 5.6789 } func ExampleAmount_FloorToCurr() { - a := money.MustParseAmount("JPY", "1.5678") - b := money.MustParseAmount("USD", "1.5678") - c := money.MustParseAmount("OMR", "1.5678") + a := money.MustParseAmount("JPY", "5.678") + b := money.MustParseAmount("USD", "5.678") + c := money.MustParseAmount("OMR", "5.678") fmt.Println(a.FloorToCurr()) fmt.Println(b.FloorToCurr()) fmt.Println(c.FloorToCurr()) // Output: - // JPY 1 - // USD 1.56 - // OMR 1.567 + // JPY 5 + // USD 5.67 + // OMR 5.678 } -func ExampleAmount_Trunc() { - a := money.MustParseAmount("USD", "15.6789") - fmt.Println(a.Trunc(5)) - fmt.Println(a.Trunc(4)) - fmt.Println(a.Trunc(3)) - fmt.Println(a.Trunc(2)) - fmt.Println(a.Trunc(1)) +func ExampleAmount_Trunc_currencies() { + a := money.MustParseAmount("JPY", "5.678") + b := money.MustParseAmount("USD", "5.678") + c := money.MustParseAmount("OMR", "5.678") fmt.Println(a.Trunc(0)) + fmt.Println(b.Trunc(0)) + fmt.Println(c.Trunc(0)) // Output: - // USD 15.6789 - // USD 15.6789 - // USD 15.678 - // USD 15.67 - // USD 15.67 - // USD 15.67 + // JPY 5 + // USD 5.67 + // OMR 5.678 +} + +func ExampleAmount_Trunc_scales() { + a := money.MustParseAmount("USD", "5.6789") + fmt.Println(a.Trunc(0)) + fmt.Println(a.Trunc(1)) + fmt.Println(a.Trunc(2)) + fmt.Println(a.Trunc(3)) + fmt.Println(a.Trunc(4)) + // Output: + // USD 5.67 + // USD 5.67 + // USD 5.67 + // USD 5.678 + // USD 5.6789 } func ExampleAmount_TruncToCurr() { - a := money.MustParseAmount("JPY", "1.5678") - b := money.MustParseAmount("USD", "1.5678") - c := money.MustParseAmount("OMR", "1.5678") + a := money.MustParseAmount("JPY", "5.678") + b := money.MustParseAmount("USD", "5.678") + c := money.MustParseAmount("OMR", "5.678") fmt.Println(a.TruncToCurr()) fmt.Println(b.TruncToCurr()) fmt.Println(c.TruncToCurr()) // Output: - // JPY 1 - // USD 1.56 - // OMR 1.567 + // JPY 5 + // USD 5.67 + // OMR 5.678 } -func ExampleAmount_Trim() { - a := money.MustParseAmount("USD", "20.0000") - fmt.Println(a.Trim(5)) - fmt.Println(a.Trim(4)) - fmt.Println(a.Trim(3)) - fmt.Println(a.Trim(2)) - fmt.Println(a.Trim(1)) +func ExampleAmount_Trim_currencies() { + a := money.MustParseAmount("JPY", "5.000") + b := money.MustParseAmount("USD", "5.000") + c := money.MustParseAmount("OMR", "5.000") fmt.Println(a.Trim(0)) + fmt.Println(b.Trim(0)) + fmt.Println(c.Trim(0)) // Output: - // USD 20.0000 - // USD 20.0000 - // USD 20.000 - // USD 20.00 - // USD 20.00 - // USD 20.00 + // JPY 5 + // USD 5.00 + // OMR 5.000 +} + +func ExampleAmount_Trim_scales() { + a := money.MustParseAmount("USD", "5.0000") + fmt.Println(a.Trim(0)) + fmt.Println(a.Trim(1)) + fmt.Println(a.Trim(2)) + fmt.Println(a.Trim(3)) + fmt.Println(a.Trim(4)) + // Output: + // USD 5.00 + // USD 5.00 + // USD 5.00 + // USD 5.000 + // USD 5.0000 } func ExampleAmount_TrimToCurr() { - a := money.MustParseAmount("JPY", "10.0000") - b := money.MustParseAmount("USD", "20.0000") - c := money.MustParseAmount("OMR", "30.0000") + a := money.MustParseAmount("JPY", "5.000") + b := money.MustParseAmount("USD", "5.000") + c := money.MustParseAmount("OMR", "5.000") fmt.Println(a.TrimToCurr()) fmt.Println(b.TrimToCurr()) fmt.Println(c.TrimToCurr()) // Output: - // JPY 10 - // USD 20.00 - // OMR 30.000 + // JPY 5 + // USD 5.00 + // OMR 5.000 } func ExampleAmount_SameCurr() { - a := money.MustParseAmount("JPY", "23.0000") - b := money.MustParseAmount("USD", "-15.670") - c := money.MustParseAmount("USD", "1.2340") + a := money.MustParseAmount("JPY", "23") + b := money.MustParseAmount("USD", "5.67") + c := money.MustParseAmount("USD", "1.23") fmt.Println(a.SameCurr(b)) fmt.Println(b.SameCurr(c)) // Output: @@ -862,84 +1267,129 @@ func ExampleAmount_SameCurr() { } func ExampleAmount_SameScale() { - a := money.MustParseAmount("USD", "23.0000") - b := money.MustParseAmount("USD", "-15.670") - c := money.MustParseAmount("USD", "1.2340") + a := money.MustParseAmount("JPY", "23") + b := money.MustParseAmount("USD", "5.67") + c := money.MustParseAmount("USD", "1.23") fmt.Println(a.SameScale(b)) - fmt.Println(a.SameScale(c)) + fmt.Println(b.SameScale(c)) // Output: // false // true } func ExampleAmount_SameScaleAsCurr() { - a := money.MustParseAmount("USD", "23.00") - b := money.MustParseAmount("OMR", "-15.670") - c := money.MustParseAmount("USD", "1.2340") + a := money.MustParseAmount("USD", "5.67") + b := money.MustParseAmount("USD", "5.678") + c := money.MustParseAmount("USD", "5.6789") fmt.Println(a.SameScaleAsCurr()) fmt.Println(b.SameScaleAsCurr()) fmt.Println(c.SameScaleAsCurr()) // Output: // true - // true + // false // false } func ExampleAmount_Scale() { a := money.MustParseAmount("USD", "23.0000") - b := money.MustParseAmount("USD", "-15.670") + b := money.MustParseAmount("USD", "5.67") fmt.Println(a.Scale()) fmt.Println(b.Scale()) // Output: // 4 + // 2 +} + +func ExampleAmount_MinScale_currencies() { + a := money.MustParseAmount("JPY", "5.0000") + b := money.MustParseAmount("USD", "5.0000") + c := money.MustParseAmount("OMR", "5.0000") + fmt.Println(a.MinScale()) + fmt.Println(b.MinScale()) + fmt.Println(c.MinScale()) + // Output: + // 0 + // 2 // 3 } -func ExampleAmount_Format() { - a := money.MustParseAmount("USD", "-123.456") +func ExampleAmount_MinScale_scales() { + a := money.MustParseAmount("USD", "5.6000") + b := money.MustParseAmount("USD", "5.6700") + c := money.MustParseAmount("USD", "5.6780") + fmt.Println(a.MinScale()) + fmt.Println(b.MinScale()) + fmt.Println(c.MinScale()) + // Output: + // 2 + // 2 + // 3 +} + +func ExampleAmount_Format_verbs() { + a := money.MustParseAmount("USD", "5.678") fmt.Printf("%v\n", a) + fmt.Printf("%[1]f %[1]c\n", a) fmt.Printf("%f\n", a) fmt.Printf("%d\n", a) fmt.Printf("%c\n", a) // Output: - // USD -123.456 - // -123.46 - // -12346 + // USD 5.678 + // 5.678 USD + // 5.678 + // 568 // USD } +func ExampleAmount_Format_currencies() { + a := money.MustParseAmount("JPY", "5") + b := money.MustParseAmount("USD", "5") + c := money.MustParseAmount("OMR", "5") + fmt.Println("| v | f | d | c |") + fmt.Println("| --------- | ----- | ---- | --- |") + fmt.Printf("| %-9[1]v | %5[1]f | %4[1]d | %[1]c |\n", a) + fmt.Printf("| %-9[1]v | %5[1]f | %4[1]d | %[1]c |\n", b) + fmt.Printf("| %-9[1]v | %5[1]f | %4[1]d | %[1]c |\n", c) + // Output: + // | v | f | d | c | + // | --------- | ----- | ---- | --- | + // | JPY 5 | 5 | 5 | JPY | + // | USD 5.00 | 5.00 | 500 | USD | + // | OMR 5.000 | 5.000 | 5000 | OMR | +} + func ExampleAmount_String() { - a := money.MustParseAmount("USD", "-1234567890.123456789") + a := money.MustParseAmount("USD", "5.67") fmt.Println(a.String()) - // Output: USD -1234567890.123456789 + // Output: USD 5.67 } func ExampleAmount_Abs() { - a := money.MustParseAmount("USD", "-15.67") + a := money.MustParseAmount("USD", "-5.67") fmt.Println(a.Abs()) - // Output: USD 15.67 + // Output: USD 5.67 } func ExampleAmount_Neg() { - a := money.MustParseAmount("USD", "15.67") + a := money.MustParseAmount("USD", "5.67") fmt.Println(a.Neg()) - // Output: USD -15.67 + // Output: USD -5.67 } func ExampleAmount_CopySign() { a := money.MustParseAmount("USD", "23.00") - b := money.MustParseAmount("USD", "-15.67") + b := money.MustParseAmount("USD", "-5.67") fmt.Println(a.CopySign(b)) fmt.Println(b.CopySign(a)) // Output: // USD -23.00 - // USD 15.67 + // USD 5.67 } func ExampleAmount_Sign() { - a := money.MustParseAmount("USD", "-15.67") - b := money.MustParseAmount("USD", "23") - c := money.MustParseAmount("USD", "0") + a := money.MustParseAmount("USD", "-5.67") + b := money.MustParseAmount("USD", "23.00") + c := money.MustParseAmount("USD", "0.00") fmt.Println(a.Sign()) fmt.Println(b.Sign()) fmt.Println(c.Sign()) @@ -950,9 +1400,9 @@ func ExampleAmount_Sign() { } func ExampleAmount_IsNeg() { - a := money.MustParseAmount("USD", "-15.67") - b := money.MustParseAmount("USD", "23") - c := money.MustParseAmount("USD", "0") + a := money.MustParseAmount("USD", "-5.67") + b := money.MustParseAmount("USD", "23.00") + c := money.MustParseAmount("USD", "0.00") fmt.Println(a.IsNeg()) fmt.Println(b.IsNeg()) fmt.Println(c.IsNeg()) @@ -963,9 +1413,9 @@ func ExampleAmount_IsNeg() { } func ExampleAmount_IsZero() { - a := money.MustParseAmount("USD", "-15.67") - b := money.MustParseAmount("USD", "23") - c := money.MustParseAmount("USD", "0") + a := money.MustParseAmount("USD", "-5.67") + b := money.MustParseAmount("USD", "23.00") + c := money.MustParseAmount("USD", "0.00") fmt.Println(a.IsZero()) fmt.Println(b.IsZero()) fmt.Println(c.IsZero()) @@ -976,8 +1426,8 @@ func ExampleAmount_IsZero() { } func ExampleAmount_IsOne() { - a := money.MustParseAmount("USD", "1") - b := money.MustParseAmount("USD", "2") + a := money.MustParseAmount("USD", "1.00") + b := money.MustParseAmount("USD", "2.00") fmt.Println(a.IsOne()) fmt.Println(b.IsOne()) // Output: @@ -986,9 +1436,9 @@ func ExampleAmount_IsOne() { } func ExampleAmount_WithinOne() { - a := money.MustParseAmount("USD", "1") - b := money.MustParseAmount("USD", "0.9") - c := money.MustParseAmount("USD", "-1") + a := money.MustParseAmount("USD", "1.00") + b := money.MustParseAmount("USD", "0.99") + c := money.MustParseAmount("USD", "-1.00") fmt.Println(a.WithinOne()) fmt.Println(b.WithinOne()) fmt.Println(c.WithinOne()) @@ -1009,9 +1459,9 @@ func ExampleAmount_IsInt() { } func ExampleAmount_IsPos() { - a := money.MustParseAmount("USD", "-15.67") - b := money.MustParseAmount("USD", "23") - c := money.MustParseAmount("USD", "0") + a := money.MustParseAmount("USD", "-5.67") + b := money.MustParseAmount("USD", "23.00") + c := money.MustParseAmount("USD", "0.00") fmt.Println(a.IsPos()) fmt.Println(b.IsPos()) fmt.Println(c.IsPos()) @@ -1021,117 +1471,10 @@ func ExampleAmount_IsPos() { // false } -func ExampleParseCurr() { - c, err := money.ParseCurr("USD") - if err != nil { - panic(err) - } - fmt.Println(c) - // Output: USD -} - -func ExampleMustParseCurr() { - c := money.MustParseCurr("USD") - fmt.Println(c) - // Output: USD -} - -func ExampleCurrency_String() { - c := money.USD - fmt.Println(c.String()) - // Output: USD -} - -func ExampleCurrency_Code() { - j := money.JPY - u := money.USD - o := money.OMR - fmt.Println(j.Code()) - fmt.Println(u.Code()) - fmt.Println(o.Code()) - // Output: - // JPY - // USD - // OMR -} - -func ExampleCurrency_Num() { - j := money.JPY - u := money.USD - o := money.OMR - fmt.Println(j.Num()) - fmt.Println(u.Num()) - fmt.Println(o.Num()) - // Output: - // 392 - // 840 - // 512 -} - -func ExampleCurrency_Scale() { - j := money.JPY - u := money.USD - o := money.OMR - fmt.Println(j.Scale()) - fmt.Println(u.Scale()) - fmt.Println(o.Scale()) - // Output: - // 0 - // 2 - // 3 -} - -func ExampleCurrency_UnmarshalText() { - c := money.XXX - b := []byte("USD") - err := c.UnmarshalText(b) - if err != nil { - panic(err) - } - fmt.Println(c) - // Output: USD -} - -func ExampleCurrency_MarshalText() { - c := money.MustParseCurr("USD") - b, err := c.MarshalText() - if err != nil { - panic(err) - } - fmt.Println(string(b)) - // Output: USD -} - -func ExampleCurrency_Scan() { - c := money.XXX - err := c.Scan("USD") - if err != nil { - panic(err) - } - fmt.Println(c) - // Output: USD -} - -func ExampleCurrency_Value() { - c := money.MustParseCurr("USD") - v, err := c.Value() - if err != nil { - panic(err) - } - fmt.Println(v) - // Output: USD -} - -func ExampleCurrency_Format() { - fmt.Printf("%c\n", money.USD) - // Output: - // USD -} - func ExampleAmount_Zero() { - a := money.MustParseAmount("JPY", "23") - b := money.MustParseAmount("JPY", "23.5") - c := money.MustParseAmount("JPY", "23.56") + a := money.MustParseAmount("JPY", "5") + b := money.MustParseAmount("JPY", "5.6") + c := money.MustParseAmount("JPY", "5.67") fmt.Println(a.Zero()) fmt.Println(b.Zero()) fmt.Println(c.Zero()) @@ -1142,9 +1485,9 @@ func ExampleAmount_Zero() { } func ExampleAmount_One() { - a := money.MustParseAmount("JPY", "23") - b := money.MustParseAmount("JPY", "23.5") - c := money.MustParseAmount("JPY", "23.56") + a := money.MustParseAmount("JPY", "5") + b := money.MustParseAmount("JPY", "5.6") + c := money.MustParseAmount("JPY", "5.67") fmt.Println(a.One()) fmt.Println(b.One()) fmt.Println(c.One()) @@ -1155,9 +1498,9 @@ func ExampleAmount_One() { } func ExampleAmount_ULP() { - a := money.MustParseAmount("JPY", "23") - b := money.MustParseAmount("JPY", "23.5") - c := money.MustParseAmount("JPY", "23.56") + a := money.MustParseAmount("JPY", "5") + b := money.MustParseAmount("JPY", "5.6") + c := money.MustParseAmount("JPY", "5.67") fmt.Println(a.ULP()) fmt.Println(b.ULP()) fmt.Println(c.ULP()) @@ -1168,12 +1511,24 @@ func ExampleAmount_ULP() { } func ExampleAmount_Cmp() { - a := money.MustParseAmount("USD", "23") - b := money.MustParseAmount("USD", "-15.67") + a := money.MustParseAmount("USD", "-23.00") + b := money.MustParseAmount("USD", "5.67") fmt.Println(a.Cmp(b)) fmt.Println(a.Cmp(a)) fmt.Println(b.Cmp(a)) // Output: + // -1 + // 0 + // 1 +} + +func ExampleAmount_CmpAbs() { + a := money.MustParseAmount("USD", "-23.00") + b := money.MustParseAmount("USD", "5.67") + fmt.Println(a.CmpAbs(b)) + fmt.Println(a.CmpAbs(a)) + fmt.Println(b.CmpAbs(a)) + // Output: // 1 // 0 // -1 @@ -1192,118 +1547,349 @@ func ExampleAmount_CmpTotal() { } func ExampleAmount_Max() { - a := money.MustParseAmount("USD", "23") - b := money.MustParseAmount("USD", "-15.67") + a := money.MustParseAmount("USD", "23.00") + b := money.MustParseAmount("USD", "-5.67") fmt.Println(a.Max(b)) // Output: USD 23.00 } func ExampleAmount_Min() { - a := money.MustParseAmount("USD", "23") - b := money.MustParseAmount("USD", "-15.67") + a := money.MustParseAmount("USD", "23.00") + b := money.MustParseAmount("USD", "-5.67") fmt.Println(a.Min(b)) - // Output: USD -15.67 + // Output: USD -5.67 +} + +func ExampleAmount_Clamp() { + min := money.MustParseAmount("USD", "-20") + max := money.MustParseAmount("USD", "20") + a := money.MustParseAmount("USD", "-5.67") + b := money.MustParseAmount("USD", "0") + c := money.MustParseAmount("USD", "23") + fmt.Println(a.Clamp(min, max)) + fmt.Println(b.Clamp(min, max)) + fmt.Println(c.Clamp(min, max)) + // Output: + // USD -5.67 + // USD 0.00 + // USD 20.00 +} + +func ExampleMustNewExchRate_scales() { + fmt.Println(money.MustNewExchRate("EUR", "USD", 567, 0)) + fmt.Println(money.MustNewExchRate("EUR", "USD", 567, 1)) + fmt.Println(money.MustNewExchRate("EUR", "USD", 567, 2)) + fmt.Println(money.MustNewExchRate("EUR", "USD", 567, 3)) + fmt.Println(money.MustNewExchRate("EUR", "USD", 567, 4)) + // Output: + // EUR/USD 567.00 + // EUR/USD 56.70 + // EUR/USD 5.67 + // EUR/USD 0.567 + // EUR/USD 0.0567 } -func ExampleNewExchRate() { - r := decimal.MustParse("1.2000") - fmt.Println(money.NewExchRate(money.USD, money.EUR, r)) - // Output: USD/EUR 1.2000 +func ExampleMustNewExchRate_currencies() { + fmt.Println(money.MustNewExchRate("EUR", "JPY", 567, 2)) + fmt.Println(money.MustNewExchRate("EUR", "USD", 567, 2)) + fmt.Println(money.MustNewExchRate("EUR", "OMR", 567, 2)) + // Output: + // EUR/JPY 5.67 + // EUR/USD 5.67 + // EUR/OMR 5.670 } -func ExampleParseExchRate() { - fmt.Println(money.ParseExchRate("USD", "EUR", "1.2000")) - // Output: USD/EUR 1.2000 +func ExampleNewExchRate_scales() { + fmt.Println(money.NewExchRate("EUR", "USD", 567, 0)) + fmt.Println(money.NewExchRate("EUR", "USD", 567, 1)) + fmt.Println(money.NewExchRate("EUR", "USD", 567, 2)) + fmt.Println(money.NewExchRate("EUR", "USD", 567, 3)) + fmt.Println(money.NewExchRate("EUR", "USD", 567, 4)) + // Output: + // EUR/USD 567.00 + // EUR/USD 56.70 + // EUR/USD 5.67 + // EUR/USD 0.567 + // EUR/USD 0.0567 } -func ExampleMustParseExchRate() { - fmt.Println(money.MustParseExchRate("OMR", "USD", "0.38497")) - // Output: OMR/USD 0.38497 +func ExampleNewExchRate_currencies() { + fmt.Println(money.NewExchRate("EUR", "JPY", 567, 2)) + fmt.Println(money.NewExchRate("EUR", "USD", 567, 2)) + fmt.Println(money.NewExchRate("EUR", "OMR", 567, 2)) + // Output: + // EUR/JPY 5.67 + // EUR/USD 5.67 + // EUR/OMR 5.670 } -func ExampleExchangeRate_Conv() { - r := money.MustParseExchRate("USD", "JPY", "133.27") - b := money.MustParseAmount("USD", "200.00") - fmt.Println(r.Conv(b)) - // Output: JPY 26654.0000 +func ExampleNewExchRateFromDecimal() { + r := decimal.MustParse("5.67") + fmt.Println(money.NewExchRateFromDecimal(money.EUR, money.JPY, r)) + fmt.Println(money.NewExchRateFromDecimal(money.EUR, money.USD, r)) + fmt.Println(money.NewExchRateFromDecimal(money.EUR, money.OMR, r)) + // Output: + // EUR/JPY 5.67 + // EUR/USD 5.67 + // EUR/OMR 5.670 } -func ExampleExchangeRate_Prec() { - r := money.MustParseExchRate("USD", "EUR", "0.9097") - q := money.MustParseExchRate("OMR", "USD", "0.38497") - fmt.Println(r.Prec()) - fmt.Println(q.Prec()) +func ExampleMustParseExchRate_currencies() { + fmt.Println(money.MustParseExchRate("EUR", "JPY", "5.67")) + fmt.Println(money.MustParseExchRate("EUR", "USD", "5.67")) + fmt.Println(money.MustParseExchRate("EUR", "OMR", "5.67")) // Output: - // 4 - // 5 + // EUR/JPY 5.67 + // EUR/USD 5.67 + // EUR/OMR 5.670 +} + +func ExampleMustParseExchRate_scales() { + fmt.Println(money.MustParseExchRate("EUR", "USD", "0.0567")) + fmt.Println(money.MustParseExchRate("EUR", "USD", "0.567")) + fmt.Println(money.MustParseExchRate("EUR", "USD", "5.67")) + fmt.Println(money.MustParseExchRate("EUR", "USD", "56.7")) + fmt.Println(money.MustParseExchRate("EUR", "USD", "567")) + // Output: + // EUR/USD 0.0567 + // EUR/USD 0.567 + // EUR/USD 5.67 + // EUR/USD 56.70 + // EUR/USD 567.00 +} + +func ExampleParseExchRate_currencies() { + fmt.Println(money.ParseExchRate("EUR", "JPY", "5.67")) + fmt.Println(money.ParseExchRate("EUR", "USD", "5.67")) + fmt.Println(money.ParseExchRate("EUR", "OMR", "5.67")) + // Output: + // EUR/JPY 5.67 + // EUR/USD 5.67 + // EUR/OMR 5.670 +} + +func ExampleParseExchRate_scales() { + fmt.Println(money.ParseExchRate("EUR", "USD", "0.0567")) + fmt.Println(money.ParseExchRate("EUR", "USD", "0.567")) + fmt.Println(money.ParseExchRate("EUR", "USD", "5.67")) + fmt.Println(money.ParseExchRate("EUR", "USD", "56.7")) + fmt.Println(money.ParseExchRate("EUR", "USD", "567")) + // Output: + // EUR/USD 0.0567 + // EUR/USD 0.567 + // EUR/USD 5.67 + // EUR/USD 56.70 + // EUR/USD 567.00 +} + +func ExampleNewExchRateFromFloat64_currencies() { + fmt.Println(money.NewExchRateFromFloat64("EUR", "JPY", 5.67e0)) + fmt.Println(money.NewExchRateFromFloat64("EUR", "USD", 5.67e0)) + fmt.Println(money.NewExchRateFromFloat64("EUR", "OMR", 5.67e0)) + // Output: + // EUR/JPY 5.67 + // EUR/USD 5.67 + // EUR/OMR 5.670 +} + +func ExampleNewExchRateFromFloat64_scales() { + fmt.Println(money.NewExchRateFromFloat64("EUR", "USD", 5.67e-2)) + fmt.Println(money.NewExchRateFromFloat64("EUR", "USD", 5.67e-1)) + fmt.Println(money.NewExchRateFromFloat64("EUR", "USD", 5.67e0)) + fmt.Println(money.NewExchRateFromFloat64("EUR", "USD", 5.67e1)) + fmt.Println(money.NewExchRateFromFloat64("EUR", "USD", 5.67e2)) + // Output: + // EUR/USD 0.0567 + // EUR/USD 0.567 + // EUR/USD 5.67 + // EUR/USD 56.70 + // EUR/USD 567.00 +} + +func ExampleNewExchRateFromInt64_scales() { + fmt.Println(money.NewExchRateFromInt64("EUR", "USD", 5, 67, 2)) + fmt.Println(money.NewExchRateFromInt64("EUR", "USD", 5, 67, 3)) + fmt.Println(money.NewExchRateFromInt64("EUR", "USD", 5, 67, 4)) + fmt.Println(money.NewExchRateFromInt64("EUR", "USD", 5, 67, 5)) + fmt.Println(money.NewExchRateFromInt64("EUR", "USD", 5, 67, 6)) + // Output: + // EUR/USD 5.67 + // EUR/USD 5.067 + // EUR/USD 5.0067 + // EUR/USD 5.00067 + // EUR/USD 5.000067 +} + +func ExampleNewExchRateFromInt64_currencies() { + fmt.Println(money.NewExchRateFromInt64("EUR", "JPY", 5, 67, 2)) + fmt.Println(money.NewExchRateFromInt64("EUR", "USD", 5, 67, 2)) + fmt.Println(money.NewExchRateFromInt64("EUR", "OMR", 5, 67, 2)) + // Output: + // EUR/JPY 5.67 + // EUR/USD 5.67 + // EUR/OMR 5.670 +} + +func ExampleExchangeRate_Conv() { + a := money.MustParseAmount("EUR", "100.00") + r := money.MustParseExchRate("EUR", "JPY", "160.00") + q := money.MustParseExchRate("EUR", "USD", "1.2500") + p := money.MustParseExchRate("EUR", "OMR", "0.42000") + fmt.Println(r.Conv(a)) + fmt.Println(q.Conv(a)) + fmt.Println(p.Conv(a)) + // Output: + // JPY 16000.0000 + // USD 125.000000 + // OMR 42.0000000 } func ExampleExchangeRate_Scale() { - r := money.MustParseExchRate("USD", "EUR", "0.9097") - q := money.MustParseExchRate("OMR", "USD", "0.38497") + r := money.MustParseExchRate("USD", "EUR", "0.80") + q := money.MustParseExchRate("OMR", "USD", "0.38000") fmt.Println(r.Scale()) fmt.Println(q.Scale()) // Output: - // 4 + // 2 // 5 } +func ExampleExchangeRate_MinScale_currencies() { + r := money.MustParseExchRate("EUR", "JPY", "5.0000") + q := money.MustParseExchRate("EUR", "USD", "5.0000") + p := money.MustParseExchRate("EUR", "OMR", "5.0000") + fmt.Println(r.MinScale()) + fmt.Println(q.MinScale()) + fmt.Println(p.MinScale()) + // Output: + // 0 + // 2 + // 3 +} + +func ExampleExchangeRate_MinScale_scales() { + r := money.MustParseExchRate("EUR", "USD", "5.6000") + q := money.MustParseExchRate("EUR", "USD", "5.6700") + p := money.MustParseExchRate("EUR", "USD", "5.6780") + fmt.Println(r.MinScale()) + fmt.Println(q.MinScale()) + fmt.Println(p.MinScale()) + // Output: + // 2 + // 2 + // 3 +} + func ExampleExchangeRate_Mul() { - r := money.MustParseExchRate("USD", "EUR", "0.9000") - e := decimal.MustParse("1.1") + r := money.MustParseExchRate("EUR", "USD", "5.67") + d := decimal.MustParse("0.9") + e := decimal.MustParse("1.0") + f := decimal.MustParse("1.1") + fmt.Println(r.Mul(d)) fmt.Println(r.Mul(e)) - // Output: USD/EUR 0.99000 + fmt.Println(r.Mul(f)) + // Output: + // EUR/USD 5.103 + // EUR/USD 5.670 + // EUR/USD 6.237 +} + +func ExampleExchangeRate_Inv_currencies() { + r := money.MustParseExchRate("EUR", "JPY", "5.67") + q := money.MustParseExchRate("EUR", "USD", "5.67") + p := money.MustParseExchRate("EUR", "OMR", "5.67") + fmt.Println(r.Inv()) + fmt.Println(q.Inv()) + fmt.Println(p.Inv()) + // Output: + // JPY/EUR 0.1763668430335097002 + // USD/EUR 0.1763668430335097002 + // OMR/EUR 0.1763668430335097002 } -func ExampleExchangeRate_Inv() { - r := money.MustParseExchRate("EUR", "USD", "1.250") +func ExampleExchangeRate_Inv_scales() { + r := money.MustParseExchRate("EUR", "USD", "0.0567") + q := money.MustParseExchRate("EUR", "USD", "0.567") + p := money.MustParseExchRate("EUR", "USD", "5.67") + o := money.MustParseExchRate("EUR", "USD", "56.7") + n := money.MustParseExchRate("EUR", "USD", "567") fmt.Println(r.Inv()) - // Output: USD/EUR 0.8000 + fmt.Println(q.Inv()) + fmt.Println(p.Inv()) + fmt.Println(o.Inv()) + fmt.Println(n.Inv()) + // Output: + // USD/EUR 17.63668430335097002 + // USD/EUR 1.763668430335097002 + // USD/EUR 0.1763668430335097002 + // USD/EUR 0.01763668430335097 + // USD/EUR 0.001763668430335097 } func ExampleExchangeRate_Base() { - r := money.MustParseExchRate("USD", "EUR", "0.9000") + r := money.MustParseExchRate("EUR", "USD", "1.2500") fmt.Println(r.Base()) - // Output: USD + // Output: EUR } func ExampleExchangeRate_Quote() { - r := money.MustParseExchRate("USD", "EUR", "0.9000") + r := money.MustParseExchRate("EUR", "USD", "1.2500") fmt.Println(r.Quote()) - // Output: EUR + // Output: USD +} + +func ExampleExchangeRate_Decimal() { + r := money.MustParseExchRate("EUR", "USD", "1.2500") + fmt.Println(r.Decimal()) + // Output: 1.2500 +} + +func ExampleExchangeRate_Float64() { + r := money.MustParseExchRate("EUR", "USD", "0.10") + q := money.MustParseExchRate("EUR", "USD", "123.456") + p := money.MustParseExchRate("EUR", "USD", "1234567890.123456789") + fmt.Println(r.Float64()) + fmt.Println(q.Float64()) + fmt.Println(p.Float64()) + // Output: + // 0.1 true + // 123.456 true + // 1.2345678901234567e+09 true +} + +func ExampleExchangeRate_Int64() { + a := money.MustParseExchRate("EUR", "USD", "5.678") + fmt.Println(a.Int64(0)) + fmt.Println(a.Int64(1)) + fmt.Println(a.Int64(2)) + fmt.Println(a.Int64(3)) + fmt.Println(a.Int64(4)) + // Output: + // 0 0 false + // 0 0 false + // 5 68 true + // 5 678 true + // 5 6780 true } func ExampleExchangeRate_SameCurr() { - r := money.MustParseExchRate("USD", "EUR", "0.9000") - q := money.MustParseExchRate("USD", "EUR", "0.9500") - p := money.MustParseExchRate("OMR", "EUR", "2.30000") + r := money.MustParseExchRate("EUR", "OMR", "0.42000") + q := money.MustParseExchRate("EUR", "USD", "1.2500") + p := money.MustParseExchRate("EUR", "USD", "5.6700") fmt.Println(r.SameCurr(q)) - fmt.Println(r.SameCurr(p)) + fmt.Println(q.SameCurr(p)) // Output: - // true // false + // true } func ExampleExchangeRate_SameScale() { - r := money.MustParseExchRate("USD", "EUR", "0.9000") - q := money.MustParseExchRate("SAR", "USD", "0.2700") - p := money.MustParseExchRate("OMR", "EUR", "2.30000") + r := money.MustParseExchRate("OMR", "EUR", "2.30000") + q := money.MustParseExchRate("USD", "EUR", "0.9000") + p := money.MustParseExchRate("SAR", "USD", "0.2700") fmt.Println(r.SameScale(q)) - fmt.Println(r.SameScale(p)) + fmt.Println(q.SameScale(p)) // Output: - // true - // false -} - -func ExampleExchangeRate_SameScaleAsCurr() { - r := money.MustParseExchRate("USD", "EUR", "0.9000") - q := money.MustParseExchRate("SAR", "USD", "0.27000") - p := money.MustParseExchRate("OMR", "EUR", "2.30000") - fmt.Println(r.SameScaleAsCurr()) - fmt.Println(q.SameScaleAsCurr()) - fmt.Println(p.SameScaleAsCurr()) - // Output: - // true // false // true } @@ -1322,20 +1908,41 @@ func ExampleExchangeRate_CanConv() { // false } -func ExampleExchangeRate_Format() { - r := money.MustParseExchRate("USD", "EUR", "1.23456") +func ExampleExchangeRate_Format_currencies() { + a := money.MustParseExchRate("EUR", "JPY", "5") + b := money.MustParseExchRate("EUR", "USD", "5") + c := money.MustParseExchRate("EUR", "OMR", "5") + fmt.Println("| v | f | b | c |") + fmt.Println("| ------------- | ----- | --- | --- |") + fmt.Printf("| %-13[1]v | %5[1]f | %[1]b | %[1]c |\n", a) + fmt.Printf("| %-13[1]v | %5[1]f | %[1]b | %[1]c |\n", b) + fmt.Printf("| %-13[1]v | %5[1]f | %[1]b | %[1]c |\n", c) + // Output: + // | v | f | b | c | + // | ------------- | ----- | --- | --- | + // | EUR/JPY 5 | 5 | EUR | JPY | + // | EUR/USD 5.00 | 5.00 | EUR | USD | + // | EUR/OMR 5.000 | 5.000 | EUR | OMR | +} + +func ExampleExchangeRate_Format_verbs() { + r := money.MustParseExchRate("USD", "EUR", "1.2500") fmt.Printf("%v\n", r) + fmt.Printf("%[1]f %[1]b-%[1]c\n", r) fmt.Printf("%f\n", r) + fmt.Printf("%b\n", r) fmt.Printf("%c\n", r) // Output: - // USD/EUR 1.23456 - // 1.2346 - // USD/EUR + // USD/EUR 1.2500 + // 1.2500 USD-EUR + // 1.2500 + // USD + // EUR } func ExampleExchangeRate_IsZero() { r := money.ExchangeRate{} - q := money.MustParseExchRate("USD", "EUR", "1.2") + q := money.MustParseExchRate("USD", "EUR", "1.25") fmt.Println(r.IsZero()) fmt.Println(q.IsZero()) // Output: @@ -1344,8 +1951,8 @@ func ExampleExchangeRate_IsZero() { } func ExampleExchangeRate_IsOne() { - r := money.MustParseExchRate("USD", "EUR", "1") - q := money.MustParseExchRate("USD", "EUR", "1.2") + r := money.MustParseExchRate("EUR", "USD", "1.00") + q := money.MustParseExchRate("EUR", "USD", "1.25") fmt.Println(r.IsOne()) fmt.Println(q.IsOne()) // Output: @@ -1353,9 +1960,29 @@ func ExampleExchangeRate_IsOne() { // false } +func ExampleExchangeRate_IsPos() { + r := money.ExchangeRate{} + q := money.MustParseExchRate("EUR", "USD", "1.25") + fmt.Println(r.IsPos()) + fmt.Println(q.IsPos()) + // Output: + // false + // true +} + +func ExampleExchangeRate_Sign() { + r := money.ExchangeRate{} + q := money.MustParseExchRate("EUR", "USD", "1.25") + fmt.Println(r.Sign()) + fmt.Println(q.Sign()) + // Output: + // 0 + // 1 +} + func ExampleExchangeRate_WithinOne() { - r := money.MustParseExchRate("EUR", "USD", "1") - q := money.MustParseExchRate("EUR", "USD", "0.8") + r := money.MustParseExchRate("EUR", "USD", "1.2500") + q := money.MustParseExchRate("USD", "EUR", "0.8000") fmt.Println(r.WithinOne()) fmt.Println(q.WithinOne()) // Output: @@ -1364,62 +1991,189 @@ func ExampleExchangeRate_WithinOne() { } func ExampleExchangeRate_String() { - r := money.MustParseExchRate("USD", "EUR", "1.2345") + r := money.MustParseExchRate("EUR", "USD", "1.2500") fmt.Println(r.String()) - // Output: USD/EUR 1.2345 + // Output: EUR/USD 1.2500 } -func ExampleExchangeRate_Rescale() { - r := money.MustParseExchRate("EUR", "USD", "1.234567") - fmt.Println(r.Rescale(7)) - fmt.Println(r.Rescale(6)) - fmt.Println(r.Rescale(5)) - fmt.Println(r.Rescale(4)) - fmt.Println(r.Rescale(3)) - fmt.Println(r.Rescale(2)) - fmt.Println(r.Rescale(1)) +func ExampleExchangeRate_Floor_currencies() { + a := money.MustParseExchRate("EUR", "JPY", "5.678") + b := money.MustParseExchRate("EUR", "USD", "5.678") + c := money.MustParseExchRate("EUR", "OMR", "5.678") + fmt.Println(a.Floor(0)) + fmt.Println(b.Floor(0)) + fmt.Println(c.Floor(0)) + // Output: + // EUR/JPY 5 + // EUR/USD 5.67 + // EUR/OMR 5.678 +} + +func ExampleExchangeRate_Floor_scales() { + a := money.MustParseExchRate("EUR", "USD", "5.6789") + fmt.Println(a.Floor(0)) + fmt.Println(a.Floor(1)) + fmt.Println(a.Floor(2)) + fmt.Println(a.Floor(3)) + fmt.Println(a.Floor(4)) + // Output: + // EUR/USD 5.67 + // EUR/USD 5.67 + // EUR/USD 5.67 + // EUR/USD 5.678 + // EUR/USD 5.6789 +} + +func ExampleExchangeRate_Rescale_currencies() { + r := money.MustParseExchRate("EUR", "JPY", "5.678") + q := money.MustParseExchRate("EUR", "USD", "5.678") + p := money.MustParseExchRate("EUR", "OMR", "5.678") fmt.Println(r.Rescale(0)) + fmt.Println(q.Rescale(0)) + fmt.Println(p.Rescale(0)) // Output: - // 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 ExampleExchangeRate_Round() { - r := money.MustParseExchRate("EUR", "USD", "1.234567") - fmt.Println(r.Round(7)) - fmt.Println(r.Round(6)) - fmt.Println(r.Round(5)) - fmt.Println(r.Round(4)) - fmt.Println(r.Round(3)) - fmt.Println(r.Round(2)) - fmt.Println(r.Round(1)) + // EUR/JPY 6 + // EUR/USD 5.68 + // EUR/OMR 5.678 +} + +func ExampleExchangeRate_Rescale_scales() { + r := money.MustParseExchRate("EUR", "USD", "5.6789") + fmt.Println(r.Rescale(0)) + fmt.Println(r.Rescale(1)) + fmt.Println(r.Rescale(2)) + fmt.Println(r.Rescale(3)) + fmt.Println(r.Rescale(4)) + // Output: + // EUR/USD 5.68 + // EUR/USD 5.68 + // EUR/USD 5.68 + // EUR/USD 5.679 + // EUR/USD 5.6789 +} + +func ExampleExchangeRate_Quantize() { + r := money.MustParseExchRate("EUR", "JPY", "5.678") + x := money.MustParseExchRate("EUR", "JPY", "1") + y := money.MustParseExchRate("EUR", "JPY", "0.1") + z := money.MustParseExchRate("EUR", "JPY", "0.01") + fmt.Println(r.Quantize(x)) + fmt.Println(r.Quantize(y)) + fmt.Println(r.Quantize(z)) + // Output: + // EUR/JPY 6 + // EUR/JPY 5.7 + // EUR/JPY 5.68 +} + +func ExampleExchangeRate_Round_currencies() { + r := money.MustParseExchRate("EUR", "JPY", "5.678") + q := money.MustParseExchRate("EUR", "USD", "5.678") + p := money.MustParseExchRate("EUR", "OMR", "5.678") fmt.Println(r.Round(0)) + fmt.Println(q.Round(0)) + fmt.Println(p.Round(0)) + // Output: + // EUR/JPY 6 + // EUR/USD 5.68 + // EUR/OMR 5.678 +} + +func ExampleExchangeRate_Round_scales() { + r := money.MustParseExchRate("EUR", "USD", "5.6789") + fmt.Println(r.Round(0)) + fmt.Println(r.Round(1)) + fmt.Println(r.Round(2)) + fmt.Println(r.Round(3)) + fmt.Println(r.Round(4)) + // Output: + // EUR/USD 5.68 + // EUR/USD 5.68 + // EUR/USD 5.68 + // EUR/USD 5.679 + // EUR/USD 5.6789 +} + +func ExampleExchangeRate_Trim_currencies() { + r := money.MustParseExchRate("EUR", "JPY", "5.000") + q := money.MustParseExchRate("EUR", "USD", "5.000") + p := money.MustParseExchRate("EUR", "OMR", "5.000") + fmt.Println(r.Trim(0)) + fmt.Println(q.Trim(0)) + fmt.Println(p.Trim(0)) + // Output: + // EUR/JPY 5 + // EUR/USD 5.00 + // EUR/OMR 5.000 +} + +func ExampleExchangeRate_Trim_scales() { + a := money.MustParseExchRate("EUR", "USD", "5.0000") + fmt.Println(a.Trim(0)) + fmt.Println(a.Trim(1)) + fmt.Println(a.Trim(2)) + fmt.Println(a.Trim(3)) + fmt.Println(a.Trim(4)) + // Output: + // EUR/USD 5.00 + // EUR/USD 5.00 + // EUR/USD 5.00 + // EUR/USD 5.000 + // EUR/USD 5.0000 +} + +func ExampleExchangeRate_Trunc_currencies() { + a := money.MustParseExchRate("EUR", "JPY", "5.678") + b := money.MustParseExchRate("EUR", "USD", "5.678") + c := money.MustParseExchRate("EUR", "OMR", "5.678") + fmt.Println(a.Trunc(0)) + fmt.Println(b.Trunc(0)) + fmt.Println(c.Trunc(0)) + // Output: + // EUR/JPY 5 + // EUR/USD 5.67 + // EUR/OMR 5.678 +} + +func ExampleExchangeRate_Trunc_scales() { + a := money.MustParseExchRate("EUR", "USD", "5.6789") + fmt.Println(a.Trunc(0)) + fmt.Println(a.Trunc(1)) + fmt.Println(a.Trunc(2)) + fmt.Println(a.Trunc(3)) + fmt.Println(a.Trunc(4)) + // Output: + // EUR/USD 5.67 + // EUR/USD 5.67 + // EUR/USD 5.67 + // EUR/USD 5.678 + // EUR/USD 5.6789 +} + +func ExampleExchangeRate_Ceil_currencies() { + r := money.MustParseExchRate("EUR", "JPY", "5.678") + q := money.MustParseExchRate("EUR", "USD", "5.678") + p := money.MustParseExchRate("EUR", "OMR", "5.678") + fmt.Println(r.Ceil(0)) + fmt.Println(q.Ceil(0)) + fmt.Println(p.Ceil(0)) + // Output: + // EUR/JPY 6 + // EUR/USD 5.68 + // EUR/OMR 5.678 +} + +func ExampleExchangeRate_Ceil_scales() { + r := money.MustParseExchRate("EUR", "USD", "5.6789") + fmt.Println(r.Ceil(0)) + fmt.Println(r.Ceil(1)) + fmt.Println(r.Ceil(2)) + fmt.Println(r.Ceil(3)) + fmt.Println(r.Ceil(4)) // Output: - // EUR/USD 1.234567 - // 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 ExampleExchangeRate_RoundToCurr() { - r := money.MustParseExchRate("USD", "JPY", "133.859") - q := money.MustParseExchRate("USD", "EUR", "0.915458") - p := money.MustParseExchRate("USD", "OMR", "0.385013") - fmt.Println(r.RoundToCurr()) - fmt.Println(q.RoundToCurr()) - fmt.Println(p.RoundToCurr()) - // Output: - // USD/JPY 133.86 - // USD/EUR 0.9155 - // USD/OMR 0.38501 + // EUR/USD 5.68 + // EUR/USD 5.68 + // EUR/USD 5.68 + // EUR/USD 5.679 + // EUR/USD 5.6789 } diff --git a/exchange_rate.go b/exchange_rate.go index 6b8aac8..277cce9 100644 --- a/exchange_rate.go +++ b/exchange_rate.go @@ -2,6 +2,9 @@ package money import ( "fmt" + "math" + "strconv" + "strings" "github.com/govalues/decimal" ) @@ -13,53 +16,197 @@ import ( type ExchangeRate struct { base Currency // currency being exchanged quote Currency // currency being obtained in exchange for the base currency - value decimal.Decimal // how many units of quote currency are needed to exchange for 1 unit of the base currency + value decimal.Decimal // how many units of quote currency are needed to exchange for one unit of the base currency } -func newExchRateUnsafe(base, quote Currency, rate decimal.Decimal) ExchangeRate { - return ExchangeRate{base: base, quote: quote, value: rate} +// newExchRateUnsafe creates a new rate without checking the sign and the scale. +// Use it only if you are absolutely sure that the arguments are valid. +func newExchRateUnsafe(b, q Currency, d decimal.Decimal) ExchangeRate { + return ExchangeRate{base: b, quote: q, value: d} } -// NewExchRate returns a new exchange rate between the base and quote currencies. -// If the scale of the rate is less than the sum of the scales of its base and -// quote currencies, the result will be zero-padded to the right. -func NewExchRate(base, quote Currency, rate decimal.Decimal) (ExchangeRate, error) { - if !rate.IsPos() { +// newExchRateSafe creates a new rate and checks the sign and the scale. +func newExchRateSafe(b, q Currency, d decimal.Decimal) (ExchangeRate, error) { + if d.IsZero() { + return ExchangeRate{}, fmt.Errorf("exchange rate must not be 0") + } + if d.IsNeg() { return ExchangeRate{}, fmt.Errorf("exchange rate must be positive") } - if base == quote && !rate.IsOne() { + if b == q && !d.IsOne() { return ExchangeRate{}, fmt.Errorf("exchange rate must be equal to 1") } - if rate.Scale() < base.Scale()+quote.Scale() { + if d.Scale() < q.Scale() { var err error - rate, err = rate.Rescale(base.Scale() + quote.Scale()) + d, err = d.Pad(q.Scale()) if err != nil { - return ExchangeRate{}, fmt.Errorf("exchange rate rescaling: %w", err) + return ExchangeRate{}, fmt.Errorf("padding exchange rate: %w", err) } } - return newExchRateUnsafe(base, quote, rate), nil + return newExchRateUnsafe(b, q, d), nil +} + +// NewExchRate returns a rate equal to coef / 10^scale. +// If the scale of the rate is less than the scale of the quote currency, the +// result will be zero-padded to the right. +// +// NewExchRate returns an error if: +// - the currency codes are not valid; +// - the coefficient is zero or negative +// - the scale is negative or greater than [decimal.MaxScale]; +// - the integer part of the result has more than +// ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when the quote currency is US Dollars, NewAmount will return an error +// if the integer part of the result has more than 17 digits (19 - 2 = 17). +func NewExchRate(base, quote string, coef int64, scale int) (ExchangeRate, error) { + // Currency + b, err := ParseCurr(base) + if err != nil { + return ExchangeRate{}, fmt.Errorf("parsing currency: %w", err) + } + q, err := ParseCurr(quote) + if err != nil { + return ExchangeRate{}, fmt.Errorf("parsing currency: %w", err) + } + // Decimal + d, err := decimal.New(coef, scale) + if err != nil { + return ExchangeRate{}, fmt.Errorf("converting coefficient: %w", err) + } + // Rate + r, err := newExchRateSafe(b, q, d) + if err != nil { + return ExchangeRate{}, fmt.Errorf("converting coefficient: %w", err) + } + return r, nil } -// ParseExchRate converts currency and decimal strings to a (possibly rounded) exchange rate. -// If the scale of the rate is less than the sum of the scales of its base and -// quote currencies, the result will be zero-padded to the right. -// See also methods [ParseCurr] and [decimal.Parse]. +// MustNewExchRate is like [NewExchRate] but panics if the rate cannot be constructed. +// It simplifies safe initialization of global variables holding rates. +func MustNewExchRate(base, quote string, coef int64, scale int) ExchangeRate { + r, err := NewExchRate(base, quote, coef, scale) + if err != nil { + panic(fmt.Sprintf("NewExchRate(%q, %q, %v, %v) failed: %v", base, quote, coef, scale, err)) + } + return r +} + +// NewExchRateFromDecimal returns a rate with the specified currencies and value. +// If the scale of the rate is less than the scale of quote currency, the result +// will be zero-padded to the right. See also method [ExchangeRate.Decimal]. +// +// NewExchRateFromDecimal returns an error if the integer part of the result has more than +// ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when the quote currency is US Dollars, NewExchRateFromDecimal will return an error if +// the integer part of the result has more than 17 digits (19 - 2 = 17). +func NewExchRateFromDecimal(base, quote Currency, rate decimal.Decimal) (ExchangeRate, error) { + return newExchRateSafe(base, quote, rate) +} + +// NewExchRateFromInt64 converts a pair of integers, representing the whole and +// fractional parts, to a (possibly rounded) rate equal to whole + frac / 10^scale. +// NewExchRateFromInt64 deletes trailing zeros up to the scale of the quote currency. +// This method is useful for converting rates from [protobuf] format. +// See also method [ExchangeRate.Int64]. +// +// NewExchRateFromInt64 returns an error if: +// - the currency codes are not valid; +// - the whole part is negative; +// - the fractional part is negative; +// - the scale is negative or greater than [decimal.MaxScale]; +// - frac / 10^scale is not within the range (-1, 1); +// - the integer part of the result has more than +// ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when the quote currency is US Dollars, NewAmountFromInt64 will return +// an error if the integer part of the result has more than 17 digits (19 - 2 = 17). +// +// [protobuf]: https://github.com/googleapis/googleapis/blob/master/google/type/money.proto +func NewExchRateFromInt64(base, quote string, whole, frac int64, scale int) (ExchangeRate, error) { + // Currency + b, err := ParseCurr(base) + if err != nil { + return ExchangeRate{}, fmt.Errorf("parsing currency: %w", err) + } + q, err := ParseCurr(quote) + if err != nil { + return ExchangeRate{}, fmt.Errorf("parsing currency: %w", err) + } + // Whole + d, err := decimal.New(whole, 0) + if err != nil { + return ExchangeRate{}, fmt.Errorf("converting integers: %w", err) + } + // Fraction + f, err := decimal.New(frac, scale) + if err != nil { + return ExchangeRate{}, fmt.Errorf("converting integers: %w", err) + } + if !f.IsZero() { + if !d.IsZero() && d.Sign() != f.Sign() { + return ExchangeRate{}, fmt.Errorf("converting integers: inconsistent signs") + } + if !f.WithinOne() { + return ExchangeRate{}, fmt.Errorf("converting integers: inconsistent fraction") + } + f = f.Trim(q.Scale()) + d, err = d.AddExact(f, q.Scale()) + if err != nil { + return ExchangeRate{}, fmt.Errorf("converting integers: %w", err) + } + } + // Amount + return newExchRateSafe(b, q, d) +} + +// NewExchRateFromFloat64 converts a float to a (possibly rounded) rate. +// See also method [ExchangeRate.Float64]. +// +// NewExchRateFromFloat64 returns an error if: +// - the currency codes are not valid; +// - the float is a zero or negative; +// - the float is a special value (NaN or Inf); +// - the integer part of the result has more than +// ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when the quote currency is US Dollars, NewExchRateFromFloat64 will +// return an error if the integer part of the result has more than 17 +// digits (19 - 2 = 17). +func NewExchRateFromFloat64(base, quote string, rate float64) (ExchangeRate, error) { + // Float + if math.IsNaN(rate) || math.IsInf(rate, 0) { + return ExchangeRate{}, fmt.Errorf("converting float: special value %v", rate) + } + s := strconv.FormatFloat(rate, 'f', -1, 64) + // Rate + r, err := ParseExchRate(base, quote, s) + if err != nil { + return ExchangeRate{}, fmt.Errorf("converting float: %w", err) + } + return r, nil +} + +// ParseExchRate converts currency and decimal strings to a (possibly rounded) rate. +// If the scale of the rate is less than the scale of the quote currency, +// the result will be zero-padded to the right. +// See also constructors [ParseCurr] and [decimal.Parse]. func ParseExchRate(base, quote, rate string) (ExchangeRate, error) { + // Currency b, err := ParseCurr(base) if err != nil { - return ExchangeRate{}, fmt.Errorf("base currency parsing: %w", err) + return ExchangeRate{}, fmt.Errorf("parsing base currency: %w", err) } q, err := ParseCurr(quote) if err != nil { - return ExchangeRate{}, fmt.Errorf("quote currency parsing: %w", err) + return ExchangeRate{}, fmt.Errorf("parsing quote currency: %w", err) } - d, err := decimal.ParseExact(rate, b.Scale()+q.Scale()) + // Decimal + d, err := decimal.ParseExact(rate, q.Scale()) if err != nil { - return ExchangeRate{}, fmt.Errorf("rate parsing: %w", err) + return ExchangeRate{}, fmt.Errorf("parsing exchange rate: %w", err) } - r, err := NewExchRate(b, q, d) + // Rate + r, err := newExchRateSafe(b, q, d) if err != nil { - return ExchangeRate{}, fmt.Errorf("rate construction: %w", err) + return ExchangeRate{}, fmt.Errorf("parsing exchange rate: %w", err) } return r, nil } @@ -84,84 +231,166 @@ func (r ExchangeRate) Quote() Currency { return r.quote } -// Mul returns an exchange rate with the same base and quote currencies, -// but with the rate multiplied by a positive factor e. +// Decimal returns the decimal representation of the rate. +func (r ExchangeRate) Decimal() decimal.Decimal { + return r.value +} + +// Float64 returns the nearest binary floating-point number rounded +// using [rounding half to even] (banker's rounding). +// See also constructor [NewExchRateFromFloat64]. // -// Mul returns an error if factor e is not positive. -func (r ExchangeRate) Mul(e decimal.Decimal) (ExchangeRate, error) { - if !e.IsPos() { - return ExchangeRate{}, fmt.Errorf("negative factor") - } - d := r.value - f, err := d.MulExact(e, r.Base().Scale()+r.Quote().Scale()) - if err != nil { - return ExchangeRate{}, fmt.Errorf("exchange rate multiplication: %w", err) +// This conversion may lose data, as float64 has a smaller precision +// than the decimal type. +// +// [rounding half to even]: https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even +func (r ExchangeRate) Float64() (f float64, ok bool) { + return r.Decimal().Float64() +} + +// Int64 returns a pair of integers representing the whole and (possibly +// rounded) fractional parts of the rate. +// If given scale is greater than the scale of the rate, then the fractional part +// is zero-padded to the right. +// If given scale is smaller than the scale of the rate, then the fractional part +// is rounded using [rounding half to even] (banker's rounding). +// The relationship between the rate and the returned values can be expressed +// as r = whole + frac / 10^scale. +// This method is useful for converting rates to [protobuf] format. +// See also constructor [NewExchRateFromInt64]. +// +// Int64 returns false if: +// - given scale is smaller than the scale of the quote currency; +// - the result cannot be represented as a pair of int64 values. +// +// [rounding half to even]: https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even +// [protobuf]: https://github.com/googleapis/googleapis/blob/master/google/type/money.proto +func (r ExchangeRate) Int64(scale int) (whole, frac int64, ok bool) { + if scale < r.Quote().Scale() { + return 0, 0, false } - return NewExchRate(r.Base(), r.Quote(), f) + return r.Decimal().Int64(scale) } // CanConv returns true if [ExchangeRate.Conv] can be used to convert the given amount. func (r ExchangeRate) CanConv(b Amount) bool { - return b.Curr() == r.Base() && + return r.Base() == b.Curr() && r.Base() != XXX && r.Quote() != XXX && - r.value.IsPos() + r.IsPos() } -// Conv returns the amount converted from the base currency to the quote currency. +// Conv returns a (possibly rounded) amount converted from the base currency to +// the quote currency. +// See also method [ExchangeRate.CanConv]. // -// Conv returns an error if the base currency of the exchange rate does not match -// the currency of the given amount. +// Conv returns an error if: +// - the base currency of the exchange rate does not match the currency of the given amount. +// - the integer part of the result has more than +// ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when converting to US Dollars, Conv will return an error +// if the integer part of the result has more than 17 digits (19 - 2 = 17). func (r ExchangeRate) Conv(b Amount) (Amount, error) { + c, err := r.conv(b) + if err != nil { + return Amount{}, fmt.Errorf("computing [%v * %v]: %w", b, r, err) + } + return c, nil +} + +func (r ExchangeRate) conv(b Amount) (Amount, error) { if !r.CanConv(b) { return Amount{}, errCurrencyMismatch } - d, e := r.value, b.value - f, err := d.MulExact(e, r.Quote().Scale()) + q, d, e := r.Quote(), r.Decimal(), b.Decimal() + d, err := d.MulExact(e, q.Scale()) if err != nil { - return Amount{}, fmt.Errorf("amount conversion: %w", err) + return Amount{}, err } - return NewAmount(r.Quote(), f) + return newAmountSafe(q, d) +} + +// Mul returns an exchange rate with the same base and quote currencies, +// but with the rate multiplied by a factor. +// +// Mul returns an error if: +// - the result is zero or negative; +// - the integer part of the result has more than +// ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when the quote currency is US Dollars, Mul will return an error +// if the integer part of the result has more than 17 digits (19 - 2 = 17). +func (r ExchangeRate) Mul(e decimal.Decimal) (ExchangeRate, error) { + q, err := r.mul(e) + if err != nil { + return ExchangeRate{}, fmt.Errorf("computing [%v * %v]: %w", r, e, err) + } + return q, nil +} + +func (r ExchangeRate) mul(e decimal.Decimal) (ExchangeRate, error) { + b, q, d := r.Base(), r.Quote(), r.Decimal() + d, err := d.MulExact(e, q.Scale()) + if err != nil { + return ExchangeRate{}, err + } + return newExchRateSafe(b, q, d) } // Inv returns the inverse of the exchange rate. +// +// Inv returns an error if: +// - the rate is zero; +// - the inverse of the rate is zero; +// - the integer part of the result has more than +// ([decimal.MaxPrec] - [Currency.Scale]) digits. +// For example, when the base currency is US Dollars, Inv will return an error +// if the integer part of the result has more than 17 digits (19 - 2 = 17). func (r ExchangeRate) Inv() (ExchangeRate, error) { - d, e := decimal.One, r.value - f, err := d.Quo(e) + q, err := r.inv() if err != nil { - return ExchangeRate{}, fmt.Errorf("exchange rate inversion: %w", err) + return ExchangeRate{}, fmt.Errorf("inverting %v: %w", r, err) } - return NewExchRate(r.Quote(), r.Base(), f) + return q, nil +} + +func (r ExchangeRate) inv() (ExchangeRate, error) { + b, q, d, e := r.Base(), r.Quote(), r.Decimal(), decimal.One + d, err := e.QuoExact(d, b.Scale()) + if err != nil { + return ExchangeRate{}, err + } + return newExchRateSafe(q, b, d) } // SameCurr returns true if exchange rates are denominated in the same base // and quote currencies. // See also methods [ExchangeRate.Base] and [ExchangeRate.Quote]. func (r ExchangeRate) SameCurr(q ExchangeRate) bool { - return q.Base() == r.Base() && q.Quote() == r.Quote() + return r.Base() == q.Base() && r.Quote() == q.Quote() } // SameScale returns true if exchange rates have the same scale. // See also method [ExchangeRate.Scale]. func (r ExchangeRate) SameScale(q ExchangeRate) bool { - return q.Scale() == r.Scale() -} - -// 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 (r ExchangeRate) SameScaleAsCurr() bool { - return r.Scale() == r.Base().Scale()+r.Quote().Scale() -} - -// Prec returns the number of digits in the coefficient. -func (r ExchangeRate) Prec() int { - return r.value.Prec() + d, e := r.Decimal(), q.Decimal() + return d.SameScale(e) } // Scale returns the number of digits after the decimal point. +// See also method [ExchangeRate.MinScale]. func (r ExchangeRate) Scale() int { - return r.value.Scale() + return r.Decimal().Scale() +} + +// MinScale returns the smallest scale that the rate can be rescaled to +// without rounding. +// See also method [ExchangeRate.Trim]. +func (r ExchangeRate) MinScale() int { + s := r.Decimal().MinScale() + if s < r.Quote().Scale() { + s = r.Quote().Scale() + } + return s } // IsZero returns: @@ -169,7 +398,23 @@ func (r ExchangeRate) Scale() int { // true if r == 0 // false otherwise func (r ExchangeRate) IsZero() bool { - return r.value.IsZero() + return r.Decimal().IsZero() +} + +// IsPos returns: +// +// true if r > 0 +// false otherwise +func (r ExchangeRate) IsPos() bool { + return r.Decimal().IsPos() +} + +// Sign returns: +// +// 0 if r = 0 +// +1 if r > 0 +func (r ExchangeRate) Sign() int { + return r.Decimal().Sign() } // IsOne returns: @@ -177,7 +422,7 @@ func (r ExchangeRate) IsZero() bool { // true if r == 1 // false otherwise func (r ExchangeRate) IsOne() bool { - return r.value.IsOne() + return r.Decimal().IsOne() } // WithinOne returns: @@ -185,46 +430,146 @@ func (r ExchangeRate) IsOne() bool { // true if 0 <= r < 1 // false otherwise func (r ExchangeRate) WithinOne() bool { - return r.value.WithinOne() + return r.Decimal().WithinOne() } -// Round returns an exchange rate that is rounded to the given number of digits -// after the decimal point. -// 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]. -func (r ExchangeRate) Round(scale int) ExchangeRate { - if scale < r.Base().Scale()+r.Quote().Scale() { - scale = r.Base().Scale() + r.Quote().Scale() +// Ceil returns a rate rounded up to the specified number of digits after +// the decimal point using [rounding toward positive infinity]. +// If the given scale is less than the scale of the quote currency, +// the rate will be rounded up to the scale of the quote currency instead. +// See also method [ExchangeRate.Floor]. +// +// [rounding toward positive infinity]: https://en.wikipedia.org/wiki/Rounding#Rounding_up +func (r ExchangeRate) Ceil(scale int) (ExchangeRate, error) { + b, q, d := r.Base(), r.Quote(), r.Decimal() + if scale < q.Scale() { + scale = q.Scale() + } + d = d.Ceil(scale) + return newExchRateSafe(b, q, d) +} + +// Floor returns a rate rounded down to the specified number of digits after +// the decimal point using [rounding toward negative infinity]. +// If the given scale is less than the scale of the quote currency, +// the rate will be rounded down to the scale of the quote currency instead. +// See also method [ExchangeRate.Ceil]. +// +// Floor returns an error if the result is zero. +// +// [rounding toward negative infinity]: https://en.wikipedia.org/wiki/Rounding#Rounding_down +func (r ExchangeRate) Floor(scale int) (ExchangeRate, error) { + b, q, d := r.Base(), r.Quote(), r.Decimal() + if scale < q.Scale() { + scale = q.Scale() + } + d = d.Floor(scale) + p, err := newExchRateSafe(b, q, d) + if err != nil { + return ExchangeRate{}, fmt.Errorf("flooring %v: %w", r, err) } - d := r.value - return newExchRateUnsafe(r.Base(), r.Quote(), d.Round(scale)) + return p, nil } -// 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 (r ExchangeRate) RoundToCurr() ExchangeRate { - return r.Round(r.Base().Scale() + r.Quote().Scale()) +// Trunc returns a rate truncated to the specified number of digits after +// the decimal point using [rounding toward zero]. +// If the given scale is less than the scale of the quote currency, +// the rate will be truncated to the scale of the quote currency instead. +// +// Trunc returns an error if the result is zero. +// +// [rounding toward zero]: https://en.wikipedia.org/wiki/Rounding#Rounding_toward_zero +func (r ExchangeRate) Trunc(scale int) (ExchangeRate, error) { + b, q, d := r.Base(), r.Quote(), r.Decimal() + if scale < q.Scale() { + scale = q.Scale() + } + d = d.Trunc(scale) + p, err := newExchRateSafe(b, q, d) + if err != nil { + return ExchangeRate{}, fmt.Errorf("truncating %v: %w", r, err) + } + return p, nil +} + +// Trim returns a rate with trailing zeros removed up to the given scale. +// If the given scale is less than the scale of the quorte currency, the +// zeros will be removed up to the scale of the quote currency instead. +func (r ExchangeRate) Trim(scale int) ExchangeRate { + b, q, d := r.Base(), r.Quote(), r.Decimal() + if scale < q.Scale() { + scale = q.Scale() + } + d = d.Trim(scale) + return newExchRateUnsafe(b, q, d) } -// Rescale returns an exchange rate that is rounded or zero-padded to the given -// number of digits after the decimal point. -// 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. +// Round returns a rate rounded to the specified number of digits after +// the decimal point using [rounding half to even] (banker's rounding). +// If the given scale is less than the scale of the quote currency, +// the rate will be rounded to the scale of the quote currency instead. +// See also method [ExchangeRate.Rescale]. +// +// Round returns an error if the result is zero. +// +// [rounding half to even]: https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even +func (r ExchangeRate) Round(scale int) (ExchangeRate, error) { + b, q, d := r.Base(), r.Quote(), r.Decimal() + if scale < q.Scale() { + scale = q.Scale() + } + d = d.Round(scale) + p, err := newExchRateSafe(b, q, d) + if err != nil { + return ExchangeRate{}, fmt.Errorf("rounding %v: %w", r, err) + } + return p, nil +} + +// Quantize returns a rate rescaled to the same scale as rate q. +// The currency and the sign of rate q are ignored. +// See also methods [ExchangeRate.Scale], [ExchangeRate.SameScale], [ExchangeRate.Rescale]. +// +// Quantize returns an error if: +// - the result is zero; +// - the integer part of the result has more than +// ([decimal.MaxPrec] - [Currency.Scale]) digits. +func (r ExchangeRate) Quantize(q ExchangeRate) (ExchangeRate, error) { + p, err := r.rescale(q.Scale()) + if err != nil { + return ExchangeRate{}, fmt.Errorf("rescaling %v to the scale of %v: %w", r, q, err) + } + return p, nil +} + +// Rescale returns a rate rounded or zero-padded to the given number of digits +// after the decimal point. +// If the specified scale is less than the scale of the quote currency, +// the amount will be rounded to the scale of the quote currency instead. +// See also method [ExchangeRate.Round]. // -// Rescale returns an error if the integer part of the result exceeds the maximum -// precision, calculated as ([decimal.MaxPrec] - scale). +// Rescale returns an error if: +// - the result is zero; +// - the integer part of the result has more than +// ([decimal.MaxPrec] - scale) digits. func (r ExchangeRate) Rescale(scale int) (ExchangeRate, error) { - if scale < r.Base().Scale()+r.Quote().Scale() { - scale = r.Base().Scale() + r.Quote().Scale() + q, err := r.rescale(scale) + if err != nil { + return ExchangeRate{}, fmt.Errorf("rescaling %v: %w", r, err) + } + return q, nil +} + +func (r ExchangeRate) rescale(scale int) (ExchangeRate, error) { + b, q, d := r.Base(), r.Quote(), r.Decimal() + if scale < q.Scale() { + scale = q.Scale() } - d := r.value d, err := d.Rescale(scale) if err != nil { - return ExchangeRate{}, fmt.Errorf("rescaling %q to %v decimal places: %w", r, scale, err) + return ExchangeRate{}, err } - return NewExchRate(r.Base(), r.Quote(), d) + return newExchRateSafe(b, q, d) } // String method implements the [fmt.Stringer] interface and returns a string @@ -234,28 +579,39 @@ func (r ExchangeRate) Rescale(scale int) (ExchangeRate, error) { // [fmt.Stringer]: https://pkg.go.dev/fmt#Stringer // [Decimal.String]: https://pkg.go.dev/github.com/govalues/decimal#Decimal.String func (r ExchangeRate) String() string { - return r.Base().String() + "/" + r.Quote().String() + " " + r.value.String() + var b strings.Builder + b.WriteString(r.Base().String()) + b.WriteByte('/') + b.WriteString(r.Quote().String()) + b.WriteByte(' ') + b.WriteString(r.Decimal().String()) + return b.String() } // Format implements the [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 +// | Verb | Example | Description | +// | ------ | ---------------- | ----------------------------- | +// | %s, %v | EUR/USD 1.2500 | Currency pair and rate | +// | %q | "EUR/USD 1.2500" | Quoted currency pair and rate | +// | %f | 1.2500 | Rate | +// | %b | EUR | Base currency | +// | %c | USD | Quote currency | // // 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. +// The default precision is equal to the actual scale of the exchange rate. // // [format verbs]: https://pkg.go.dev/fmt#hdr-Printing // [fmt.Formatter]: https://pkg.go.dev/fmt#Formatter // //gocyclo:ignore func (r ExchangeRate) Format(state fmt.State, verb rune) { + b, q, d := r.Base(), r.Quote(), r.Decimal() + // Rescaling tzeroes := 0 if verb == 'f' || verb == 'F' { @@ -264,27 +620,30 @@ func (r ExchangeRate) Format(state fmt.State, verb rune) { case ok: scale = p default: - scale = r.Base().Scale() + r.Quote().Scale() + scale = d.Scale() + } + if scale < q.Scale() { + scale = q.Scale() } switch { - case scale < r.Scale(): - r = r.Round(scale) - case scale > r.Scale(): - tzeroes = scale - r.Scale() + case scale < d.Scale(): + d = d.Round(scale) + case scale > d.Scale(): + tzeroes = scale - d.Scale() } } // Integer and fractional digits intdigs, fracdigs := 0, 0 - switch rprec := r.Prec(); verb { - case 'c', 'C': + switch rprec := d.Prec(); verb { + case 'b', 'B', 'c', 'C': // skip default: - fracdigs = r.Scale() + fracdigs = d.Scale() if rprec > fracdigs { intdigs = rprec - fracdigs } - if r.WithinOne() { + if d.WithinOne() { intdigs++ // leading 0 } } @@ -295,17 +654,26 @@ func (r ExchangeRate) Format(state fmt.State, verb rune) { dpoint = 1 } - // Currency symbols - curr := "" + // Currency codes and delimiters + basecode, quocode := "", "" + basesyms, quosyms, pairdel, currdel := 0, 0, 0, 0 switch verb { case 'f', 'F': // skip + case 'b', 'B': + basecode = b.Code() + basesyms = len(basecode) case 'c', 'C': - curr = r.Base().String() + "/" + r.Quote().String() + quocode = q.Code() + quosyms = len(quocode) default: - curr = r.Base().String() + "/" + r.Quote().String() + " " + basecode = b.Code() + quocode = q.Code() + basesyms = len(basecode) + quosyms = len(quocode) + pairdel = 1 + currdel = 1 } - currlen := len(curr) // Opening and closing quotes lquote, tquote := 0, 0 @@ -314,13 +682,13 @@ func (r ExchangeRate) Format(state fmt.State, verb rune) { } // Calculating padding - width := lquote + intdigs + dpoint + fracdigs + tzeroes + currlen + tquote + width := lquote + basesyms + pairdel + quosyms + currdel + intdigs + dpoint + fracdigs + tzeroes + tquote lspaces, lzeroes, tspaces := 0, 0, 0 if w, ok := state.Width(); ok && w > width { switch { case state.Flag('-'): tspaces = w - width - case state.Flag('0') && verb != 'c' && verb != 'C': + case state.Flag('0') && verb != 'c' && verb != 'C' && verb != 'b' && verb != 'B': lzeroes = w - width default: lspaces = w - width @@ -350,7 +718,7 @@ func (r ExchangeRate) Format(state fmt.State, verb rune) { } // Fractional digits - coef := r.value.Coef() + coef := d.Coef() for i := 0; i < fracdigs; i++ { buf[pos] = byte(coef%10) + '0' pos-- @@ -376,9 +744,27 @@ func (r ExchangeRate) Format(state fmt.State, verb rune) { pos-- } - // Currency symbols - for i := currlen; i > 0; i-- { - buf[pos] = curr[i-1] + // Currency delimiter + if currdel > 0 { + buf[pos] = ' ' + pos-- + } + + // Quote currency + for i := quosyms; i > 0; i-- { + buf[pos] = quocode[i-1] + pos-- + } + + // Pair delimiter + if pairdel > 0 { + buf[pos] = '/' + pos-- + } + + // Base currency + for i := basesyms; i > 0; i-- { + buf[pos] = basecode[i-1] pos-- } @@ -396,7 +782,7 @@ func (r ExchangeRate) Format(state fmt.State, verb rune) { // Writing result switch verb { - case 'q', 'Q', 's', 'S', 'v', 'V', 'f', 'F', 'c', 'C': + case 'q', 'Q', 's', 'S', 'v', 'V', 'f', 'F', 'b', 'B', 'c', 'C': state.Write(buf) default: state.Write([]byte("%!")) diff --git a/exchange_rate_test.go b/exchange_rate_test.go index 9b2816e..1e73048 100644 --- a/exchange_rate_test.go +++ b/exchange_rate_test.go @@ -2,6 +2,7 @@ package money import ( "fmt" + "math" "testing" "unsafe" @@ -19,7 +20,7 @@ func TestExchangeRate_ZeroValue(t *testing.T) { t.Errorf("ExchangeRate{}.Quote() = %v, want %v", got.Quote(), XXX) } if !got.IsZero() { - t.Errorf("ExchangeRate{}.value.IsZero() = %v, want %v", got.IsZero(), true) + t.Errorf("ExchangeRate{}.IsZero() = %v, want %v", got.IsZero(), true) } } @@ -32,7 +33,212 @@ func TestExchangeRate_Sizeof(t *testing.T) { } } +func TestMustNewExchRate(t *testing.T) { + t.Run("error", func(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("MustNewExchRate(\"EUR\", \"USD\", 0, -1) did not panic") + } + }() + MustNewExchRate("EUR", "USD", 0, -1) + }) +} + +func TestMustParseExchRate(t *testing.T) { + t.Run("error", func(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Errorf("MustParseExchRate(\"EUR\", \"USD\", \".\") did not panic") + } + }() + MustParseExchRate("EUR", "USD", ".") + }) +} + func TestNewExchRate(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + base, quote string + coef int64 + scale int + want string + }{ + {"EUR", "JPY", math.MaxInt64, 0, "9223372036854775807"}, + {"EUR", "JPY", math.MaxInt64, 19, "0.9223372036854775807"}, + {"EUR", "USD", math.MaxInt64, 2, "92233720368547758.07"}, + {"EUR", "USD", math.MaxInt64, 19, "0.9223372036854775807"}, + {"EUR", "OMR", math.MaxInt64, 3, "9223372036854775.807"}, + {"EUR", "OMR", math.MaxInt64, 19, "0.9223372036854775807"}, + } + for _, tt := range tests { + got, err := NewExchRate(tt.base, tt.quote, tt.coef, tt.scale) + if err != nil { + t.Errorf("NewExchRate(%q, %q, %v, %v) failed: %v", tt.base, tt.quote, tt.coef, tt.scale, err) + continue + } + want := MustParseExchRate(tt.base, tt.quote, tt.want) + if got != want { + t.Errorf("NewExchRate(%q, %q, %v, %v) = %q, want %q", tt.base, tt.quote, tt.coef, tt.scale, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + base, quote string + coef int64 + scale int + }{ + "base currency 1": {"EEE", "USD", 1, 0}, + "quote currency 1": {"EUR", "UUU", 1, 0}, + "scale range 1": {"EUR", "USD", 1, -1}, + "scale range 2": {"EUR", "USD", 1, 20}, + "coefficient 1": {"EUR", "USD", 0, 0}, + "coefficient 2": {"EUR", "USD", -1, 0}, + "coefficient 3": {"EUR", "EUR", 2, 0}, + "overflow 1": {"EUR", "USD", math.MaxInt64, 0}, + "overflow 2": {"EUR", "USD", math.MaxInt64, 1}, + "overflow 3": {"EUR", "USD", math.MinInt64, 0}, + "overflow 4": {"EUR", "USD", math.MinInt64, 1}, + "overflow 5": {"EUR", "OMR", math.MaxInt64, 0}, + "overflow 6": {"EUR", "OMR", math.MaxInt64, 1}, + "overflow 7": {"EUR", "OMR", math.MaxInt64, 2}, + "overflow 8": {"EUR", "OMR", math.MinInt64, 0}, + "overflow 9": {"EUR", "OMR", math.MinInt64, 1}, + "overflow 10": {"EUR", "OMR", math.MinInt64, 2}, + } + for _, tt := range tests { + _, err := NewExchRate(tt.base, tt.quote, tt.coef, tt.scale) + if err == nil { + t.Errorf("NewExchRate(%q, %q, %v, %v) did not fail", tt.base, tt.quote, tt.coef, tt.scale) + } + } + }) +} + +func TestNewExchRateFromInt64(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + base, quote string + whole, frac int64 + scale int + want string + }{ + {"EUR", "USD", 1, 1, 1, "1.10"}, + {"EUR", "USD", 1, 1, 2, "1.01"}, + {"EUR", "USD", 1, 1, 3, "1.001"}, + {"EUR", "USD", 1, 100000000, 9, "1.10"}, + {"EUR", "USD", 1, 1, 18, "1.000000000000000001"}, + {"EUR", "USD", 1, 1, 19, "1.000000000000000000"}, + {"EUR", "JPY", math.MaxInt64, math.MaxInt32, 10, "9223372036854775807"}, + {"EUR", "JPY", math.MaxInt64, math.MaxInt64, 19, "9223372036854775808"}, + } + for _, tt := range tests { + got, err := NewExchRateFromInt64(tt.base, tt.quote, tt.whole, tt.frac, tt.scale) + if err != nil { + t.Errorf("NewExchRateFromInt64(%q, %q, %v, %v, %v) failed: %v", tt.base, tt.quote, tt.whole, tt.frac, tt.scale, err) + continue + } + want := MustParseExchRate(tt.base, tt.quote, tt.want) + if got != want { + t.Errorf("NewExchRateFromInt64(%q, %q, %v, %v, %v) = %q, want %q", tt.base, tt.quote, tt.whole, tt.frac, tt.scale, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + base, quote string + whole, frac int64 + scale int + }{ + "quote currency 1": {"EUR", "UUU", 1, 0, 0}, + "base currency 1": {"EEE", "USD", 1, 0, 0}, + "different signs 1": {"EUR", "USD", -1, 1, 0}, + "fraction range 1": {"EUR", "USD", 1, 1, 0}, + "scale range 1": {"EUR", "USD", 1, 1, -1}, + "scale range 2": {"EUR", "USD", 1, 0, -1}, + "scale range 3": {"EUR", "USD", 1, 1, 20}, + "scale range 4": {"EUR", "USD", 1, 0, 20}, + "overflow 1": {"EUR", "USD", 100000000000000000, 100000000000000000, 18}, + "overflow 2": {"EUR", "USD", 999999999999999999, 9, 1}, + "overflow 3": {"EUR", "USD", 999999999999999999, 99, 2}, + "overflow 4": {"EUR", "USD", math.MaxInt64, math.MaxInt32, 10}, + "overflow 5": {"EUR", "OMR", math.MaxInt64, math.MaxInt32, 10}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + _, err := NewExchRateFromInt64(tt.base, tt.quote, tt.whole, tt.frac, tt.scale) + if err == nil { + t.Errorf("NewExchRateFromInt64(%q, %q, %v, %v, %v) did not fail", tt.base, tt.quote, tt.whole, tt.frac, tt.scale) + } + }) + } + }) +} + +func TestNewExchRateFromFloat64(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + base, quote string + f float64 + want string + }{ + {"EUR", "USD", 1e-19, "0.0000000000000000001"}, + {"EUR", "USD", 1e-5, "0.00001"}, + {"EUR", "USD", 1e-4, "0.0001"}, + {"EUR", "USD", 1e-3, "0.001"}, + {"EUR", "USD", 1e-2, "0.01"}, + {"EUR", "USD", 1e-1, "0.1"}, + {"EUR", "USD", 1e0, "1"}, + {"EUR", "USD", 1e1, "10"}, + {"EUR", "USD", 1e2, "100"}, + {"EUR", "USD", 1e3, "1000"}, + {"EUR", "USD", 1e4, "10000"}, + {"EUR", "USD", 1e5, "100000"}, + {"EUR", "JPY", 1e18, "1000000000000000000"}, + {"EUR", "USD", 1e16, "10000000000000000"}, + {"EUR", "OMR", 1e15, "1000000000000000"}, + } + for _, tt := range tests { + got, err := NewExchRateFromFloat64(tt.base, tt.quote, tt.f) + if err != nil { + t.Errorf("NewExchRateFromFloat64(%q, %q, %v) failed: %v", tt.base, tt.quote, tt.f, err) + continue + } + want := MustParseExchRate(tt.base, tt.quote, tt.want) + if got != want { + t.Errorf("NewExchRateFromFloat64(%q, %q, %v) = %q, want %q", tt.base, tt.quote, tt.f, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + base, quote string + f float64 + }{ + "base currency 1": {"EEE", "USD", 1}, + "quote currency 1": {"EUR", "ZZZ", 1}, + "overflow 1": {"EUR", "JPY", 1e19}, + "overflow 2": {"EUR", "USD", 1e17}, + "overflow 3": {"EUR", "OMR", 1e16}, + "special value 1": {"EUR", "USD", math.NaN()}, + "special value 2": {"EUR", "USD", math.Inf(1)}, + "special value 3": {"EUR", "USD", math.Inf(-1)}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + _, err := NewExchRateFromFloat64(tt.base, tt.quote, tt.f) + if err == nil { + t.Errorf("NewExchRateFromFloat64(%q, %q, %v) did not fail", tt.base, tt.quote, tt.f) + } + }) + } + }) +} + +func TestNewExchRateFromDecimal(t *testing.T) { tests := []struct { b, q Currency r string @@ -43,18 +249,18 @@ func TestNewExchRate(t *testing.T) { {USD, USD, "0.9999", false}, {USD, USD, "1.0000", true}, {USD, USD, "1.0001", false}, - {USD, JPY, "100000000000000000", false}, - {USD, EUR, "1000000000000000", false}, - {USD, OMR, "100000000000000", false}, + {USD, JPY, "1000000000000000000", true}, + {USD, EUR, "100000000000000000", false}, + {USD, OMR, "10000000000000000", false}, } for _, tt := range tests { rate := decimal.MustParse(tt.r) - _, err := NewExchRate(tt.b, tt.q, rate) + _, err := NewExchRateFromDecimal(tt.b, tt.q, rate) if !tt.wantOk && err == nil { - t.Errorf("NewExchError(%v, %v, %v) did not fail", tt.b, tt.q, rate) + t.Errorf("NewExchRateFromDecimal(%v, %v, %v) did not fail", tt.b, tt.q, rate) } if tt.wantOk && err != nil { - t.Errorf("NewExchRate(%v, %v, %v) failed: %v", tt.b, tt.q, rate, err) + t.Errorf("NewExchRateFromDecimal(%v, %v, %v) failed: %v", tt.b, tt.q, rate, err) } } } @@ -68,8 +274,8 @@ func TestParseExchRate(t *testing.T) { wantScale int }{ {"USD", "JPY", "132", USD, JPY, 132, 0}, - {"USD", "EUR", "1.2", USD, EUR, 12000, 4}, - {"USD", "OMR", "0.38", USD, OMR, 38000, 5}, + {"USD", "EUR", "1.25", USD, EUR, 125, 2}, + {"USD", "OMR", "0.38", USD, OMR, 380, 3}, } for _, tt := range tests { got, err := ParseExchRate(tt.b, tt.q, tt.r) @@ -82,7 +288,7 @@ func TestParseExchRate(t *testing.T) { t.Errorf("decimal.New(%v, %v) failed: %v", tt.wantCoef, tt.wantScale, err) continue } - want, err := NewExchRate(tt.wantBase, tt.wantQuote, wantRate) + want, err := NewExchRateFromDecimal(tt.wantBase, tt.wantQuote, wantRate) if err != nil { t.Errorf("NewExchRate(%v, %v, %v) failed: %v", tt.wantBase, tt.wantQuote, wantRate, err) continue @@ -97,13 +303,13 @@ func TestParseExchRate(t *testing.T) { tests := map[string]struct { b, q, r string }{ - "no data": {"", "", ""}, - "base 1": {"AAA", "USD", "30000"}, - "quote 1": {"USD", "AAA", "0.00003"}, - "rate 1": {"USD", "EUR", "x.0000"}, - "rate 2": {"USD", "USD", "0.9999"}, - "rate 3": {"USD", "EUR", "0.0"}, - "rate 4": {"USD", "EUR", "-0.9999"}, + "no data": {"", "", ""}, + "base currency 1": {"AAA", "USD", "30000"}, + "quote currency 1": {"USD", "AAA", "0.00003"}, + "invalid rate 1": {"USD", "EUR", "x.0000"}, + "invalid rate 2": {"USD", "USD", "0.9999"}, + "invalid rate 3": {"USD", "EUR", "0.0"}, + "invalid rate 4": {"USD", "EUR", "-0.9999"}, } for _, tt := range tests { _, err := ParseExchRate(tt.b, tt.q, tt.r) @@ -126,10 +332,10 @@ func TestExchangeRate_Mul(t *testing.T) { {"USD", "EUR", "5", "1", "5"}, {"USD", "EUR", "5", "2", "10"}, {"USD", "EUR", "1.20", "2", "2.40"}, - {"USD", "EUR", "5.09", "7.1", "36.13900"}, + {"USD", "EUR", "5.09", "7.1", "36.139"}, {"USD", "EUR", "2.5", "4", "10.0"}, {"USD", "EUR", "2.50", "4", "10.00"}, - {"USD", "EUR", "0.70", "1.05", "0.735000"}, + {"USD", "EUR", "0.70", "1.05", "0.7350"}, } for _, tt := range tests { r := MustParseExchRate(tt.b, tt.q, tt.r) @@ -150,8 +356,8 @@ func TestExchangeRate_Mul(t *testing.T) { tests := map[string]struct { b, q, r, f string }{ - "overflow 1": {"USD", "EUR", "0.9", "10000000000000000"}, - "overflow 2": {"USD", "EUR", "100000000000000", "10"}, + "overflow 1": {"USD", "EUR", "0.9", "1000000000000000000"}, + "overflow 2": {"USD", "EUR", "10000000000000000", "10"}, "factor 1": {"USD", "EUR", "0.9", "0.0"}, "factor 2": {"USD", "EUR", "0.9", "-0.1"}, } @@ -196,28 +402,6 @@ func TestExchangeRate_Inv(t *testing.T) { }) } -func TestExchangeRate_SameScaleAsCurr(t *testing.T) { - tests := []struct { - b, q, r string - want bool - }{ - {"USD", "EUR", "1", true}, - {"USD", "EUR", "1.0", true}, - {"USD", "EUR", "1.00", true}, - {"USD", "EUR", "1.000", true}, - {"USD", "EUR", "1.0000", true}, - {"USD", "EUR", "1.00000", false}, - {"USD", "EUR", "1.000000", false}, - } - for _, tt := range tests { - r := MustParseExchRate(tt.b, tt.q, tt.r) - got := r.SameScaleAsCurr() - if got != tt.want { - t.Errorf("%q.SameScaleAsCurr() = %v, want %v", r, got, tt.want) - } - } -} - func TestExchangeRate_Conv(t *testing.T) { t.Run("success", func(t *testing.T) { tests := []struct { @@ -268,91 +452,105 @@ func TestExchangeRate_Format(t *testing.T) { b, q, r, format, want string }{ // %T verb - {"USD", "EUR", "100.00", "%T", "money.ExchangeRate"}, + {"USD", "EUR", "100.0000", "%T", "money.ExchangeRate"}, // %q verb - {"USD", "EUR", "100.00", "%q", "\"USD/EUR 100.0000\""}, - {"USD", "EUR", "100.00", "%+q", "\"USD/EUR 100.0000\""}, // '+' is ignored - {"USD", "EUR", "100.00", "% q", "\"USD/EUR 100.0000\""}, // ' ' is ignored - {"USD", "EUR", "100.00", "%.6q", "\"USD/EUR 100.0000\""}, // precision is ignored - {"USD", "EUR", "100.00", "%16q", "\"USD/EUR 100.0000\""}, - {"USD", "EUR", "100.00", "%17q", "\"USD/EUR 100.0000\""}, - {"USD", "EUR", "100.00", "%18q", "\"USD/EUR 100.0000\""}, - {"USD", "EUR", "100.00", "%19q", " \"USD/EUR 100.0000\""}, - {"USD", "EUR", "100.00", "%019q", "\"USD/EUR 0100.0000\""}, - {"USD", "EUR", "100.00", "%+19q", " \"USD/EUR 100.0000\""}, // '+' is ignored - {"USD", "EUR", "100.00", "%-19q", "\"USD/EUR 100.0000\" "}, - {"USD", "EUR", "100.00", "%+-021q", "\"USD/EUR 100.0000\" "}, // '+' and '0' are ignored + {"USD", "EUR", "100.0000", "%q", "\"USD/EUR 100.0000\""}, + {"USD", "EUR", "100.0000", "%+q", "\"USD/EUR 100.0000\""}, // '+' is ignored + {"USD", "EUR", "100.0000", "% q", "\"USD/EUR 100.0000\""}, // ' ' is ignored + {"USD", "EUR", "100.0000", "%.6q", "\"USD/EUR 100.0000\""}, // precision is ignored + {"USD", "EUR", "100.0000", "%16q", "\"USD/EUR 100.0000\""}, + {"USD", "EUR", "100.0000", "%17q", "\"USD/EUR 100.0000\""}, + {"USD", "EUR", "100.0000", "%18q", "\"USD/EUR 100.0000\""}, + {"USD", "EUR", "100.0000", "%19q", " \"USD/EUR 100.0000\""}, + {"USD", "EUR", "100.0000", "%019q", "\"USD/EUR 0100.0000\""}, + {"USD", "EUR", "100.0000", "%+19q", " \"USD/EUR 100.0000\""}, // '+' is ignored + {"USD", "EUR", "100.0000", "%-19q", "\"USD/EUR 100.0000\" "}, + {"USD", "EUR", "100.0000", "%+-021q", "\"USD/EUR 100.0000\" "}, // '+' and '0' are ignored // %s verb - {"USD", "EUR", "100.00", "%s", "USD/EUR 100.0000"}, - {"USD", "EUR", "100.00", "%+s", "USD/EUR 100.0000"}, // '+' is ignored - {"USD", "EUR", "100.00", "% s", "USD/EUR 100.0000"}, // ' ' is ignored - {"USD", "EUR", "100.00", "%.6s", "USD/EUR 100.0000"}, // precision is ignored - {"USD", "EUR", "100.00", "%16s", "USD/EUR 100.0000"}, - {"USD", "EUR", "100.00", "%17s", " USD/EUR 100.0000"}, - {"USD", "EUR", "100.00", "%18s", " USD/EUR 100.0000"}, - {"USD", "EUR", "100.00", "%19s", " USD/EUR 100.0000"}, - {"USD", "EUR", "100.00", "%019s", "USD/EUR 000100.0000"}, - {"USD", "EUR", "100.00", "%+19s", " USD/EUR 100.0000"}, // '+' is ignored - {"USD", "EUR", "100.00", "%-19s", "USD/EUR 100.0000 "}, - {"USD", "EUR", "100.00", "%+-021s", "USD/EUR 100.0000 "}, // '+' and '0' are ignored + {"USD", "EUR", "100.0000", "%s", "USD/EUR 100.0000"}, + {"USD", "EUR", "100.0000", "%+s", "USD/EUR 100.0000"}, // '+' is ignored + {"USD", "EUR", "100.0000", "% s", "USD/EUR 100.0000"}, // ' ' is ignored + {"USD", "EUR", "100.0000", "%.6s", "USD/EUR 100.0000"}, // precision is ignored + {"USD", "EUR", "100.0000", "%16s", "USD/EUR 100.0000"}, + {"USD", "EUR", "100.0000", "%17s", " USD/EUR 100.0000"}, + {"USD", "EUR", "100.0000", "%18s", " USD/EUR 100.0000"}, + {"USD", "EUR", "100.0000", "%19s", " USD/EUR 100.0000"}, + {"USD", "EUR", "100.0000", "%019s", "USD/EUR 000100.0000"}, + {"USD", "EUR", "100.0000", "%+19s", " USD/EUR 100.0000"}, // '+' is ignored + {"USD", "EUR", "100.0000", "%-19s", "USD/EUR 100.0000 "}, + {"USD", "EUR", "100.0000", "%+-021s", "USD/EUR 100.0000 "}, // '+' and '0' are ignored // %v verb - {"USD", "EUR", "100.00", "%v", "USD/EUR 100.0000"}, - {"USD", "EUR", "100.00", "%+v", "USD/EUR 100.0000"}, // '+' is ignored - {"USD", "EUR", "100.00", "% v", "USD/EUR 100.0000"}, // ' ' is ignored - {"USD", "EUR", "100.00", "%.6v", "USD/EUR 100.0000"}, // precision is ignored - {"USD", "EUR", "100.00", "%16v", "USD/EUR 100.0000"}, - {"USD", "EUR", "100.00", "%17v", " USD/EUR 100.0000"}, - {"USD", "EUR", "100.00", "%18v", " USD/EUR 100.0000"}, - {"USD", "EUR", "100.00", "%19v", " USD/EUR 100.0000"}, - {"USD", "EUR", "100.00", "%019v", "USD/EUR 000100.0000"}, - {"USD", "EUR", "100.00", "%+19v", " USD/EUR 100.0000"}, // '+' is ignored - {"USD", "EUR", "100.00", "%-19v", "USD/EUR 100.0000 "}, - {"USD", "EUR", "100.00", "%+-021v", "USD/EUR 100.0000 "}, // '+' and '0' are ignored + {"USD", "EUR", "100.0000", "%v", "USD/EUR 100.0000"}, + {"USD", "EUR", "100.0000", "%+v", "USD/EUR 100.0000"}, // '+' is ignored + {"USD", "EUR", "100.0000", "% v", "USD/EUR 100.0000"}, // ' ' is ignored + {"USD", "EUR", "100.0000", "%.6v", "USD/EUR 100.0000"}, // precision is ignored + {"USD", "EUR", "100.0000", "%16v", "USD/EUR 100.0000"}, + {"USD", "EUR", "100.0000", "%17v", " USD/EUR 100.0000"}, + {"USD", "EUR", "100.0000", "%18v", " USD/EUR 100.0000"}, + {"USD", "EUR", "100.0000", "%19v", " USD/EUR 100.0000"}, + {"USD", "EUR", "100.0000", "%019v", "USD/EUR 000100.0000"}, + {"USD", "EUR", "100.0000", "%+19v", " USD/EUR 100.0000"}, // '+' is ignored + {"USD", "EUR", "100.0000", "%-19v", "USD/EUR 100.0000 "}, + {"USD", "EUR", "100.0000", "%+-021v", "USD/EUR 100.0000 "}, // '+' and '0' are ignored // %f verb {"JPY", "EUR", "0.01", "%f", "0.01"}, {"JPY", "EUR", "100.00", "%f", "100.00"}, - {"OMR", "EUR", "0.01", "%f", "0.01000"}, - {"OMR", "EUR", "100.00", "%f", "100.00000"}, - {"USD", "EUR", "0.01", "%f", "0.0100"}, - {"USD", "EUR", "100.00", "%f", "100.0000"}, - {"USD", "EUR", "9.996208266660", "%f", "9.9962"}, - {"USD", "EUR", "0.9996208266660", "%f", "0.9996"}, - {"USD", "EUR", "0.09996208266660", "%f", "0.1000"}, - {"USD", "EUR", "0.009996208266660", "%f", "0.0100"}, - {"USD", "EUR", "100.00", "%+f", "100.0000"}, // '+' is ignored - {"USD", "EUR", "100.00", "% f", "100.0000"}, // ' ' is ignored - {"USD", "EUR", "100.00", "%.3f", "100.0000"}, // precision cannot be smaller than curr scale - {"USD", "EUR", "100.00", "%.4f", "100.0000"}, - {"USD", "EUR", "100.00", "%.5f", "100.00000"}, - {"USD", "EUR", "100.00", "%.6f", "100.000000"}, - {"USD", "EUR", "100.00", "%.7f", "100.0000000"}, - {"USD", "EUR", "100.00", "%.8f", "100.00000000"}, - {"USD", "EUR", "100.00", "%9f", " 100.0000"}, - {"USD", "EUR", "100.00", "%10f", " 100.0000"}, - {"USD", "EUR", "100.00", "%11f", " 100.0000"}, - {"USD", "EUR", "100.00", "%12f", " 100.0000"}, - {"USD", "EUR", "100.00", "%013f", "00000100.0000"}, - {"USD", "EUR", "100.00", "%+13f", " 100.0000"}, // '+' is ignored - {"USD", "EUR", "100.00", "%-13f", "100.0000 "}, + {"OMR", "EUR", "0.01", "%f", "0.01"}, + {"OMR", "EUR", "100.00", "%f", "100.00"}, + {"USD", "EUR", "0.01", "%f", "0.01"}, + {"USD", "EUR", "100.00", "%f", "100.00"}, + {"USD", "EUR", "9.996208266660", "%.1f", "10.00"}, + {"USD", "EUR", "0.9996208266660", "%.1f", "1.00"}, + {"USD", "EUR", "0.09996208266660", "%.1f", "0.10"}, + {"USD", "EUR", "0.009996208266660", "%.1f", "0.01"}, + {"USD", "EUR", "0.0009996208266660", "%.1f", "0.00"}, + {"USD", "EUR", "9.996208266660", "%.4f", "9.9962"}, + {"USD", "EUR", "0.9996208266660", "%.4f", "0.9996"}, + {"USD", "EUR", "0.09996208266660", "%.4f", "0.1000"}, + {"USD", "EUR", "0.009996208266660", "%.4f", "0.0100"}, + {"USD", "EUR", "100.0000", "%+f", "100.0000"}, // '+' is ignored + {"USD", "EUR", "100.0000", "% f", "100.0000"}, // ' ' is ignored + {"USD", "EUR", "100.0000", "%.3f", "100.000"}, + {"USD", "EUR", "100.0000", "%.4f", "100.0000"}, + {"USD", "EUR", "100.0000", "%.5f", "100.00000"}, + {"USD", "EUR", "100.0000", "%.6f", "100.000000"}, + {"USD", "EUR", "100.0000", "%.7f", "100.0000000"}, + {"USD", "EUR", "100.0000", "%.8f", "100.00000000"}, + {"USD", "EUR", "100.0000", "%9f", " 100.0000"}, + {"USD", "EUR", "100.0000", "%10f", " 100.0000"}, + {"USD", "EUR", "100.0000", "%11f", " 100.0000"}, + {"USD", "EUR", "100.0000", "%12f", " 100.0000"}, + {"USD", "EUR", "100.0000", "%013f", "00000100.0000"}, + {"USD", "EUR", "100.0000", "%+13f", " 100.0000"}, // '+' is ignored + {"USD", "EUR", "100.0000", "%-13f", "100.0000 "}, + // %b verb + {"USD", "EUR", "100.00", "%b", "USD"}, + {"USD", "EUR", "100.00", "%+b", "USD"}, // '+' is ignored + {"USD", "EUR", "100.00", "% b", "USD"}, // ' ' is ignored + {"USD", "EUR", "100.00", "%#b", "USD"}, // '#' is ignored + {"USD", "EUR", "100.00", "%9b", " USD"}, + {"USD", "EUR", "100.00", "%09b", " USD"}, // '0' is ignored + {"USD", "EUR", "100.00", "%#9b", " USD"}, // '#' is ignored + {"USD", "EUR", "100.00", "%-9b", "USD "}, + {"USD", "EUR", "100.00", "%-#9b", "USD "}, // '#' is ignored // %c verb - {"USD", "EUR", "100.00", "%c", "USD/EUR"}, - {"USD", "EUR", "100.00", "%+c", "USD/EUR"}, // '+' is ignored - {"USD", "EUR", "100.00", "% c", "USD/EUR"}, // ' ' is ignored - {"USD", "EUR", "100.00", "%#c", "USD/EUR"}, // '#' is ignored - {"USD", "EUR", "100.00", "%9c", " USD/EUR"}, - {"USD", "EUR", "100.00", "%09c", " USD/EUR"}, // '0' is ignored - {"USD", "EUR", "100.00", "%#9c", " USD/EUR"}, // '#' is ignored - {"USD", "EUR", "100.00", "%-9c", "USD/EUR "}, - {"USD", "EUR", "100.00", "%-#9c", "USD/EUR "}, // '#' is ignored + {"USD", "EUR", "100.00", "%c", "EUR"}, + {"USD", "EUR", "100.00", "%+c", "EUR"}, // '+' is ignored + {"USD", "EUR", "100.00", "% c", "EUR"}, // ' ' is ignored + {"USD", "EUR", "100.00", "%#c", "EUR"}, // '#' is ignored + {"USD", "EUR", "100.00", "%9c", " EUR"}, + {"USD", "EUR", "100.00", "%09c", " EUR"}, // '0' is ignored + {"USD", "EUR", "100.00", "%#9c", " EUR"}, // '#' is ignored + {"USD", "EUR", "100.00", "%-9c", "EUR "}, + {"USD", "EUR", "100.00", "%-#9c", "EUR "}, // '#' is ignored // wrong verbs - {"USD", "EUR", "12.34", "%b", "%!b(money.ExchangeRate=USD/EUR 12.3400)"}, - {"USD", "EUR", "12.34", "%d", "%!d(money.ExchangeRate=USD/EUR 12.3400)"}, - {"USD", "EUR", "12.34", "%e", "%!e(money.ExchangeRate=USD/EUR 12.3400)"}, - {"USD", "EUR", "12.34", "%E", "%!E(money.ExchangeRate=USD/EUR 12.3400)"}, - {"USD", "EUR", "12.34", "%g", "%!g(money.ExchangeRate=USD/EUR 12.3400)"}, - {"USD", "EUR", "12.34", "%G", "%!G(money.ExchangeRate=USD/EUR 12.3400)"}, - {"USD", "EUR", "12.34", "%x", "%!x(money.ExchangeRate=USD/EUR 12.3400)"}, - {"USD", "EUR", "12.34", "%X", "%!X(money.ExchangeRate=USD/EUR 12.3400)"}, + {"USD", "EUR", "12.3400", "%d", "%!d(money.ExchangeRate=USD/EUR 12.3400)"}, + {"USD", "EUR", "12.3400", "%e", "%!e(money.ExchangeRate=USD/EUR 12.3400)"}, + {"USD", "EUR", "12.3400", "%E", "%!E(money.ExchangeRate=USD/EUR 12.3400)"}, + {"USD", "EUR", "12.3400", "%g", "%!g(money.ExchangeRate=USD/EUR 12.3400)"}, + {"USD", "EUR", "12.3400", "%G", "%!G(money.ExchangeRate=USD/EUR 12.3400)"}, + {"USD", "EUR", "12.3400", "%x", "%!x(money.ExchangeRate=USD/EUR 12.3400)"}, + {"USD", "EUR", "12.3400", "%X", "%!X(money.ExchangeRate=USD/EUR 12.3400)"}, } for _, tt := range tests { r := MustParseExchRate(tt.b, tt.q, tt.r) @@ -362,3 +560,268 @@ func TestExchangeRate_Format(t *testing.T) { } } } + +func TestExchangeRate_Ceil(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + b, q, r string + scale int + want string + }{ + {"USD", "EUR", "0.8000", 2, "0.80"}, + } + for _, tt := range tests { + r := MustParseExchRate(tt.b, tt.q, tt.r) + got, err := r.Ceil(tt.scale) + if err != nil { + t.Errorf("%q.Ceil(%v) failed: %v", r, tt.scale, err) + continue + } + want := MustParseExchRate(tt.b, tt.q, tt.want) + if got != want { + t.Errorf("%q.Ceil(%v) = %q, want %q", r, tt.scale, got, want) + } + } + }) +} + +func TestExchangeRate_Floor(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + b, q, r string + scale int + want string + }{ + {"USD", "EUR", "0.8000", 0, "0.80"}, + {"USD", "EUR", "0.0800", 1, "0.08"}, + } + for _, tt := range tests { + r := MustParseExchRate(tt.b, tt.q, tt.r) + got, err := r.Floor(tt.scale) + if err != nil { + t.Errorf("%q.Floor(%v) failed: %v", r, tt.scale, err) + continue + } + want := MustParseExchRate(tt.b, tt.q, tt.want) + if got != want { + t.Errorf("%q.Floor(%v) = %q, want %q", r, tt.scale, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + base, quote, r string + scale int + }{ + "zero rate 1": {"USD", "EUR", "0.0080", 2}, + "zero rate 2": {"USD", "EUR", "0.0008", 3}, + } + for _, tt := range tests { + r := MustParseExchRate(tt.base, tt.quote, tt.r) + _, err := r.Floor(tt.scale) + if err == nil { + t.Errorf("%q.Floor(%v) did not fail", r, tt.scale) + } + } + }) +} + +func TestExchangeRate_Trunc(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + base, quote, r string + scale int + want string + }{ + {"USD", "EUR", "0.8000", 2, "0.80"}, + {"USD", "EUR", "0.0800", 2, "0.08"}, + } + for _, tt := range tests { + r := MustParseExchRate(tt.base, tt.quote, tt.r) + got, err := r.Trunc(tt.scale) + if err != nil { + t.Errorf("%q.Trunc(%v) failed: %v", r, tt.scale, err) + continue + } + want := MustParseExchRate(tt.base, tt.quote, tt.want) + if got != want { + t.Errorf("%q.Trunc(%v) = %q, want %q", r, tt.scale, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + base, quote, r string + scale int + }{ + "zero rate 1": {"USD", "EUR", "0.0080", 2}, + "zero rate 2": {"USD", "EUR", "0.0008", 3}, + } + for _, tt := range tests { + r := MustParseExchRate(tt.base, tt.quote, tt.r) + _, err := r.Trunc(tt.scale) + if err == nil { + t.Errorf("%q.Trunc(%v) did not fail", r, tt.scale) + } + } + }) +} + +func TestExchangeRate_Round(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + base, quote, r string + scale int + want string + }{ + {"USD", "EUR", "0.8000", 2, "0.80"}, + {"USD", "EUR", "0.0800", 2, "0.08"}, + {"USD", "EUR", "0.0080", 2, "0.01"}, + } + for _, tt := range tests { + r := MustParseExchRate(tt.base, tt.quote, tt.r) + got, err := r.Round(tt.scale) + if err != nil { + t.Errorf("%q.Round(%v) failed: %v", r, tt.scale, err) + continue + } + want := MustParseExchRate(tt.base, tt.quote, tt.want) + if got != want { + t.Errorf("%q.Round(%v) = %q, want %q", r, tt.scale, got, want) + } + } + }) + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + base, quote, r string + scale int + }{ + "zero rate 1": {"USD", "EUR", "0.0050", 2}, + "zero rate 2": {"USD", "EUR", "0.0005", 3}, + } + for _, tt := range tests { + r := MustParseExchRate(tt.base, tt.quote, tt.r) + _, err := r.Round(tt.scale) + if err == nil { + t.Errorf("%q.Round(%v) did not fail", r, tt.scale) + } + } + }) +} + +func TestExchangeRate_Rescale(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + base, quote, r string + scale int + want string + }{ + // Padding + {"EUR", "JPY", "1", 0, "1"}, + {"EUR", "JPY", "1", 1, "1.0"}, + {"EUR", "JPY", "1", 2, "1.00"}, + {"EUR", "JPY", "1", 3, "1.000"}, + {"EUR", "USD", "1", 0, "1.00"}, + {"EUR", "USD", "1", 1, "1.00"}, + {"EUR", "USD", "1", 2, "1.00"}, + {"EUR", "USD", "1", 3, "1.000"}, + {"EUR", "OMR", "1", 0, "1.000"}, + {"EUR", "OMR", "1", 1, "1.000"}, + {"EUR", "OMR", "1", 2, "1.000"}, + {"EUR", "OMR", "1", 3, "1.000"}, + {"EUR", "USD", "1", 17, "1.00000000000000000"}, + {"EUR", "USD", "1", 18, "1.000000000000000000"}, + {"EUR", "USD", "1", 17, "1.00000000000000000"}, + {"EUR", "USD", "1", 18, "1.000000000000000000"}, + + // Half-to-even rounding + {"EUR", "USD", "0.0051", 2, "0.01"}, + {"EUR", "USD", "0.0149", 2, "0.01"}, + {"EUR", "USD", "0.0151", 2, "0.02"}, + {"EUR", "USD", "0.0150", 2, "0.02"}, + {"EUR", "USD", "0.0250", 2, "0.02"}, + {"EUR", "USD", "0.0350", 2, "0.04"}, + {"EUR", "USD", "3.0448", 2, "3.04"}, + {"EUR", "USD", "3.0450", 2, "3.04"}, + {"EUR", "USD", "3.0452", 2, "3.05"}, + {"EUR", "USD", "3.0956", 2, "3.10"}, + } + for _, tt := range tests { + r := MustParseExchRate(tt.base, tt.quote, tt.r) + got, err := r.Rescale(tt.scale) + if err != nil { + t.Errorf("%q.Rescale(%v) failed: %v", r, tt.scale, err) + continue + } + want := MustParseExchRate(tt.base, tt.quote, tt.want) + if got != want { + t.Errorf("%q.Rescale(%v) = %q, want %q", r, tt.scale, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + base, quote, r string + scale int + }{ + "zero rate 1": {"USD", "EUR", "0.0050", 2}, + "zero rate 2": {"USD", "EUR", "0.0005", 3}, + "scale 1": {"USD", "EUR", "0.0005", 20}, + } + for _, tt := range tests { + r := MustParseExchRate(tt.base, tt.quote, tt.r) + _, err := r.Rescale(tt.scale) + if err == nil { + t.Errorf("%q.Rescale(%v) did not fail", r, tt.scale) + } + } + }) +} + +func TestExchangeRate_Quantize(t *testing.T) { + t.Run("success", func(t *testing.T) { + tests := []struct { + base, quote, r, q string + want string + }{ + {"EUR", "JPY", "1", "0.01", "1.00"}, + {"EUR", "JPY", "1", "0.001", "1.000"}, + {"EUR", "JPY", "1", "0.0001", "1.0000"}, + {"EUR", "JPY", "1", "0.00001", "1.00000"}, + {"EUR", "JPY", "1", "0.000001", "1.000000"}, + } + for _, tt := range tests { + r := MustParseExchRate(tt.base, tt.quote, tt.r) + q := MustParseExchRate(tt.base, tt.quote, tt.q) + got, err := r.Quantize(q) + if err != nil { + t.Errorf("%q.Quantize(%q) failed: %v", r, q, err) + continue + } + want := MustParseExchRate(tt.base, tt.quote, tt.want) + if got != want { + t.Errorf("%q.Quantize(%q) = %q, want %q", r, q, got, want) + } + } + }) + + t.Run("error", func(t *testing.T) { + tests := map[string]struct { + base, quote, r, q string + }{ + "zero rate 1": {"USD", "EUR", "0.0050", "0.01"}, + "zero rate 2": {"USD", "EUR", "0.0005", "0.001"}, + } + for _, tt := range tests { + r := MustParseExchRate(tt.base, tt.quote, tt.r) + q := MustParseExchRate(tt.base, tt.quote, tt.q) + _, err := r.Quantize(q) + if err == nil { + t.Errorf("%q.Quantize(%q) did not fail", r, q) + } + } + }) +} diff --git a/go.mod b/go.mod index 7399a18..7891f3d 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,4 @@ module github.com/govalues/money go 1.20 -require github.com/govalues/decimal v0.1.8 +require github.com/govalues/decimal v0.1.17 diff --git a/go.sum b/go.sum index 6452738..6d0b4f0 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,2 @@ -github.com/govalues/decimal v0.1.8 h1:60HMvHhjt6Tagn+CGFzSZV35V/U6WaBtVsCvYjQd7MI= -github.com/govalues/decimal v0.1.8/go.mod h1:irMp3+UfATz5dlLhUagswX2ATLhGDmo/Hoq2MP4/9gg= +github.com/govalues/decimal v0.1.17 h1:7TSPB6tyONvdnd6F8qMnBHOsAw6ffIMBytGb5FY0yPg= +github.com/govalues/decimal v0.1.17/go.mod h1:irMp3+UfATz5dlLhUagswX2ATLhGDmo/Hoq2MP4/9gg= diff --git a/scripts/currency/currency_data.tmpl b/scripts/currency/currency_data.tmpl index 809d82c..07f4221 100644 --- a/scripts/currency/currency_data.tmpl +++ b/scripts/currency/currency_data.tmpl @@ -15,7 +15,7 @@ var currLookup = map[string]Currency { {{ end -}} } -var scaleLookup = [...]int{ +var scaleLookup = [...]int8{ {{ range $curr := . -}} {{ $curr.Scale }}, // {{ $curr.Name }} {{ end -}}