money

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: May 5, 2023 License: MIT Imports: 13 Imported by: 0

README

D3money testing state

A library to handle monetary values and currencies.

This library is still in development. While it works and most of its functionality is tested by unit tests, the API may have breaking changes until version 1.0.0 is reached.

Features

  • Uses shopspring/decimal for arbitrary precision fixed-point decimal numbers.
  • Values are immutable by default.
  • ISO 4217 currencies.
  • Extensible with custom currencies.
  • Tests to ensure uniqueness and correctness of currencies (including user-defined ones).
  • Useful mathematical operations, including a way to split a monetary value into n parts.
  • Data bindings for JSON, binary, text, gob encodings.
  • Implements scanner and valuer interfaces for databases.
  • Implements GormDBDataTypeInterface.
  • Supports postgresql composite types.

Planned:

  • Include cryptocurrencies and tokens.
  • Split locale and currency information.
  • Formatting of values with specified locale. Support CLDR as good as possible, also go generate support to convert LDML based data into go code and structures.
  • Migration field for currencies, e.g. to describe how custom currencies will map to official supported currencies.
  • Generate currency data from the official ISO 4217 sources via go generate.

What this is not

A high performance library to do number crunching with. Although this library is not slow, it is not intended for processing large tables of monetary values. The focus of this library is on correctness and ease of use.

Usage

To be able to use this library, first download it via

go get github.com/Dadido3/D3money

And then import it with

import money "github.com/Dadido3/D3money"
Values

A simple way to create a monetary value is by using FromString(...).

value1, err := money.FromString("123.45 ISO4217-EUR") // Value with ISO4217 EUR as currency.
value2, err := money.FromString("123.45")             // Value without currency or unit.

It's also possible to create a value by using a currency object.

value, err := money.FromStringAndCurrency("123.45", money.Currencies.ByUniqueCode("ISO4217-EUR"))

For non user-input strings, the MustFrom... variants can be used. They will not return any error, but panic if something is wrong.

value1 := money.MustFromString("123.45 ISO4217-EUR")
value2 := money.MustFromStringAndCurrency("123.45 ISO4217-EUR", money.Currencies.ByUniqueCode("ISO4217-EUR"))
value3 := money.MustFromString("123.45 FOO-BAR") // Will panic if FOO-BAR is not a registered currency.
Currencies

Selecting from all available currencies.

eur := money.Currencies.ByUniqueCode("ISO4217-EUR")

Selecting a currency from ISO 4217 by its code or unique code.

usd := money.ISO4217Currencies.ByCode("USD")
eur := money.ISO4217Currencies.ByUniqueCode("ISO4217-EUR")

Assert currency standard.

eur := money.Currencies.ByUniqueCode("ISO4217-EUR")
_, isISO4217 := eur.(money.ISO4217Currency) // isISO4217 will be true
Custom currencies

To create custom currencies, you need to create a type that implements the money.Currency interface. For an example, see currency-iso4217.go.

You can check if your instances are valid by using.

err := money.ValidateCurrency(customCurrency)

Afterwards you can register the currency by adding it to the library by using.

err := money.Currencies.Add(customCurrency)      // Register single custom currency.
err := money.Currencies.Add(customCurrencies...) // Register list of custom currencies.

If you add custom currencies, make sure to only use negative unique IDs to prevent ID collisions with official currencies in the future.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Currencies = MustNewCurrencyCollection("D3money-currencies", "", iso4217Currencies)

Currencies contains all the currencies that come with this library. This will be used for unmarshalling or for scanning from a database.

If you want to add custom currencies, add them to this collection by using

Currencies.Add(CustomCurrency)
Currencies.Add(CustomCurrency1, CustomCurrency2)
Currencies.Add(CustomCurrencies...)
View Source
var ISO4217Currencies = MustNewCurrencyCollection(iso4217Name, iso4217Name, iso4217Currencies)

ISO4217Currencies currencies according to ISO 4217.

Functions

func ValidateCurrency

func ValidateCurrency(c Currency) error

ValidateCurrency checks if the given currency contains illegal characters and such things.

Types

type Currency

type Currency interface {
	Name() string     // Name returns the name of the currency. This is the english or native name.
	Standard() string // Standard returns an alphanumeric string that identifies the standard the currency is defined in.

	UniqueID() int32                       // UniqueID returns the unique ID of the currency. This is specific to this library. All positive IDs are reserved for use in this library. If you add your own currencies use negative numbers to prevent collisions with the built in currencies in the future.
	UniqueCode() string                    // Code returns a string representing the currency. This representation is unique across different currency standards. Examples: "ISO4217-USD", "ISO4217-AUD", "ISO4217-EUR", "CRYPTO-BTC".
	NumericCode() int                      // NumericCode returns the numeric code of the currency. This may be an ISO 4217 numeric code, depending on the currency type and is unique in a single currency standard. Examples: 840, 36, 978.
	Code() string                          // Code returns a string representing the currency. This may be an ISO 4217 code, depending on the currency type and is unique in a single currency standard. Examples: "USD", "AUD", "EUR", "BTC".
	Symbol(lang language.Tag) string       // Symbol returns a string containing the symbol of the currency. This may be ambiguous, and should only be used for formatting into a human readable format. Examples: "US$", "AU$", "€", "₿"
	NarrowSymbol(lang language.Tag) string // NarrowSymbol returns a string containing the narrow symbol variant of the currency. This may be ambiguous, and should only be used for formatting into a human readable format. This needs additional context when used in text output, otherwise there is no way to differentiate between AUD and USD for example. Examples: "$", "$", "€", "₿".

	SmallestUnit() Value // SmallestUnit returns the value of the fractional unit. This can be any value, even one that is larger than 1. A value of 0 means that there is no smallest unit.
}

Currency defines a currency and its properties.

type CurrencyCollection

type CurrencyCollection struct {
	// contains filtered or unexported fields
}

CurrencyCollection is a container for currencies.

func MustNewCurrencyCollection

func MustNewCurrencyCollection(name string, currencyStandard string, listsOfCurrencies ...[]Currency) *CurrencyCollection

MustNewCurrencyCollection takes one or more list of currencies and returns them as a collection.

With currencyStandard you can limit the collection to only allow currencies of a specific standard. Set it to "" if you want to allow multiple currency standards.

It will panic on any error.

func NewCurrencyCollection

func NewCurrencyCollection(name string, currencyStandard string, listsOfCurrencies ...[]Currency) (*CurrencyCollection, error)

NewCurrencyCollection takes one or more lists of currencies and returns them as a collection.

With currencyStandard you can limit the collection to only allow currencies of a specific standard. Set it to "" if you want to allow multiple currency standards.

func (*CurrencyCollection) Add

func (cc *CurrencyCollection) Add(currencies ...Currency) error

Add adds one or more currencies to this collection.

func (*CurrencyCollection) All

func (cc *CurrencyCollection) All() []Currency

All returns the full list of currencies that are contained in this collection.

func (*CurrencyCollection) ByCode

func (cc *CurrencyCollection) ByCode(code string) Currency

ByCode finds a currency by its code (e.g. "EUR"). This may not yield a result, as the code is not unique across currency standards. Best is to use it only in combination with a collection of a single standard, like ISO4217Currencies.

func (*CurrencyCollection) ByNumericCode added in v0.2.0

func (cc *CurrencyCollection) ByNumericCode(numericCode int) Currency

ByNumericCode finds a currency by its numeric code (e.g. 978). This may not yield a result, as the numeric code is not unique across currency standards. Best is to use it only in combination with a collection of a single standard, like ISO4217Currencies.

func (*CurrencyCollection) ByUniqueCode

func (cc *CurrencyCollection) ByUniqueCode(uniqueCode string) Currency

ByUniqueCode finds a currency by its unique code (e.g. "ISO4217-EUR").

func (*CurrencyCollection) ByUniqueID

func (cc *CurrencyCollection) ByUniqueID(uniqueID int32) Currency

ByUniqueID finds a currency by its unique ID (e.g. 42170978).

func (*CurrencyCollection) CurrencyStandard added in v0.2.0

func (cc *CurrencyCollection) CurrencyStandard() string

Name returns the name of the currency standard. If this collection can contain multiple standards, this will return "".

func (*CurrencyCollection) Name

func (cc *CurrencyCollection) Name() string

Name returns the name of the currency collection.

type ErrorCantFindUniqueCode added in v0.2.0

type ErrorCantFindUniqueCode struct {
	// contains filtered or unexported fields
}

ErrorCantFindUniqueCode is returned when no currency can be found for a given unique code.

func (*ErrorCantFindUniqueCode) Error added in v0.2.0

func (e *ErrorCantFindUniqueCode) Error() string

type ErrorCantFindUniqueID added in v0.2.0

type ErrorCantFindUniqueID struct {
	// contains filtered or unexported fields
}

ErrorCantFindUniqueID is returned when no currency can be found for a given unique ID.

func (*ErrorCantFindUniqueID) Error added in v0.2.0

func (e *ErrorCantFindUniqueID) Error() string

type ErrorDifferentCurrencies added in v0.2.0

type ErrorDifferentCurrencies struct {
	// contains filtered or unexported fields
}

ErrorDifferentCurrencies is returned when the currencies between two values don't match.

func (*ErrorDifferentCurrencies) Error added in v0.2.0

func (e *ErrorDifferentCurrencies) Error() string

type ErrorInvalidCurrency added in v0.2.0

type ErrorInvalidCurrency struct {
	// contains filtered or unexported fields
}

ErrorInvalidCurrency is returned when the definition of a currency contains invalid or illegal values.

func (*ErrorInvalidCurrency) Error added in v0.2.0

func (e *ErrorInvalidCurrency) Error() string

type ISO4217Currency

type ISO4217Currency struct {
	// contains filtered or unexported fields
}

ISO4217Currency defines a currency according to the ISO 4217 standard.

func (*ISO4217Currency) Code

func (c *ISO4217Currency) Code() string

Code returns a string representing the currency. This is the official code defined by the standard, but it may not be unique across different standards. This may be an ISO 4217 code, depending on the currency type.

Examples: "USD", "AUD", "EUR", "BTC".

func (*ISO4217Currency) CodePrefix

func (c *ISO4217Currency) CodePrefix() string

CodePrefix is the prefix that is used to generate the unique currency code.

func (*ISO4217Currency) Name

func (c *ISO4217Currency) Name() string

Name returns the name of the currency. This is the english or native name.

func (*ISO4217Currency) NarrowSymbol added in v0.2.0

func (c *ISO4217Currency) NarrowSymbol(lang language.Tag) string

NarrowSymbol returns a string containing the narrow symbol variant of the currency. This may be ambiguous, and should only be used for formatting into a human readable format. This needs additional context when used in text output, as it doesn't differentiate between all the dollar currencies.

Examples: "$", "$", "€", "₿".

func (*ISO4217Currency) NumericCode added in v0.2.0

func (c *ISO4217Currency) NumericCode() int

NumericCode returns the numeric code of the currency. This may be an ISO 4217 numeric code, depending on the currency type and is unique in a single currency standard.

Examples: 840, 36, 978.

func (*ISO4217Currency) SmallestUnit added in v0.2.0

func (c *ISO4217Currency) SmallestUnit() Value

SmallestUnit returns the value of the fractional unit. This can be any value, even one that is larger than 1. A value of 0 means that there is no smallest unit.

func (*ISO4217Currency) Standard added in v0.2.0

func (c *ISO4217Currency) Standard() string

Standard returns an alphanumeric string that identifies the standard the currency is defined in.

func (*ISO4217Currency) String

func (c *ISO4217Currency) String() string

func (*ISO4217Currency) Symbol

func (c *ISO4217Currency) Symbol(lang language.Tag) string

Symbol returns a string containing the symbol of the currency. This may be ambiguous, and should only be used for formatting into a human readable format.

Examples: "US$", "AU$", "€", "₿".

func (*ISO4217Currency) UniqueCode

func (c *ISO4217Currency) UniqueCode() string

Code returns a string representing the currency. This representation is unique across different currency standards.

Examples: "ISO4217-USD", "ISO4217-AUD", "ISO4217-EUR", "CRYPTO-BTC".

func (*ISO4217Currency) UniqueID

func (c *ISO4217Currency) UniqueID() int32

UniqueID returns the unique ID of the currency. This is specific to this library.

All positive IDs are reserved for use in this library. If you add your own currencies use negative numbers to prevent collisions with the built in currencies in the future.

type Value

type Value struct {
	// contains filtered or unexported fields
}

Value represents a monetary value in a specific currency.

func FromDecimal added in v0.2.0

func FromDecimal(amount decimal.Decimal, cur Currency) Value

FromDecimal returns a value object from the given shopspring/decimal and currency.

func FromFloat32 added in v0.2.0

func FromFloat32(f float32, cur Currency) Value

FromFloat32 returns a value object from the given float32 and currency.

func FromFloat64 added in v0.2.0

func FromFloat64(f float64, cur Currency) Value

FromFloat64 returns a value object from the given float64 and currency.

func FromInt32 added in v0.2.0

func FromInt32(i int32, cur Currency) Value

FromInt32 returns a value object from the given int32 and currency.

func FromInt64 added in v0.2.0

func FromInt64(i int64, cur Currency) Value

FromInt64 returns a value object from the given int64 and currency.

func FromString

func FromString(str string) (Value, error)

FromString returns a value object from the given string. The string can contain a currency by its unique code. This will not use any locale specific formatting, and is not suited for input from humans without any preprocessing.

Examples:

FromString("-10000.123")             // Returns a currency-less value.
FromString("-10000.123 ISO4217-EUR") // Returns a value with the EUR currency defined by ISO 4217.
FromString("-10000.123 EUR")         // Returns an error, as the currency in the string can't be matched/found.
FromString("-10000.123 FOO-BAR")     // Result depends on whether the the custom currency "FOO-BAR" is registered. See `Currencies.Add(...)`.

func FromStringAndCurrency

func FromStringAndCurrency(str string, cur Currency) (Value, error)

FromStringAndCurrency returns a value object from the given string. The field cur can be used to define the currency. The string can contain a currency by its unique code, but if it does, it must match the currency in the field cur. This will not use any locale specific formatting, and is not suited for input from humans without any preprocessing.

Examples:

FromStringAndCurrency("-10000.123", nil)                                         // Returns a currency-less value.
FromStringAndCurrency("-10000.123 ISO4217-EUR", nil)                             // Returns an error, as the currency differs from the one defined in field cur.
FromStringAndCurrency("-10000.123", ISO4217Currencies.ByCode("EUR"))             // Returns a value with EUR currency.
FromStringAndCurrency("-10000.123 ISO4217-EUR", ISO4217Currencies.ByCode("EUR")) // Returns a value with EUR currency.
FromStringAndCurrency("-10000.123 ISO4217-USD", ISO4217Currencies.ByCode("EUR")) // Returns an error, as the currency differs from the one defined in field cur.
FromStringAndCurrency("-10000.123 FOO-BAR", nil)                                 // Returns an error, as the currency differs from the one defined in field cur.
FromStringAndCurrency("-10000.123", FooBarCurrency)                              // Returns a value with custom currency.
FromStringAndCurrency("-10000.123 FOO-BAR", FooBarCurrency)                      // Returns a value with custom currency. This assumes that the unique code of that currency is "FOO-BAR".

func MustFromString

func MustFromString(str string) Value

MustFromString returns a value object from the given string. The string can contain a currency by its unique code. This will not use any locale specific formatting, and is not suited for input from humans without any preprocessing.

In case of an error, this will panic.

For examples, see FromString().

func MustFromStringAndCurrency

func MustFromStringAndCurrency(str string, cur Currency) Value

MustFromStringAndCurrency returns a value object from the given string. The field cur can be used to define the currency. The string can contain a currency by its unique code, but if it does, it must match the currency in the field cur. This will not use any locale specific formatting, and is not suited for input from humans without any preprocessing.

In case of an error, this will panic.

For examples, see FromStringAndCurrency().

func MustSum added in v0.2.0

func MustSum(first Value, values ...Value) Value

MustSum returns the sum of all given values. The currencies must not differ.

Use this version if you have already made sure that the currencies are equal between all values.

func Sum added in v0.2.0

func Sum(first Value, values ...Value) (Value, error)

Sum returns the sum of all given values. The currencies must not differ.

Sum(MustFromString("12.34 ISO4217-EUR"), MustFromString("12.34 ISO4217-EUR")) // Returns 24.68 ISO4217-EUR.
Sum(MustFromString("12.34 ISO4217-EUR"), MustFromString("12.34"))             // Returns an error.

func (Value) Abs added in v0.2.0

func (v Value) Abs() Value

Abs returns the absolute value.

MustFromString("-123.456 ISO4217-EUR").Abs() // Returns "123.456 ISO4217-EUR"
MustFromString("123.456 ISO4217-EUR").Abs()  // Returns "123.456 ISO4217-EUR"

func (Value) Add added in v0.2.0

func (v Value) Add(v2 Value) (Value, error)

Add returns v + v2 as a new value. It will not mutate either v or v2.

In case the two values don't use the same currency, this will return an error.

func (Value) Currency

func (v Value) Currency() Currency

Currency returns the used currency.

func (Value) Decimal

func (v Value) Decimal() decimal.Decimal

Decimal returns the value as a shopspring/decimal number.

func (Value) Equal

func (v Value) Equal(comp Value) bool

Equal returns if a monetary value is equal to another. If the currency differs between the two values, the result is always false.

func (Value) EqualDetailed added in v0.3.0

func (v Value) EqualDetailed(comp Value) (bool, error)

EqualDetailed returns if a monetary value is equal to another. If the currency differs between the two values, the result is always false and an error is returned.

func (Value) Float64 added in v0.2.0

func (v Value) Float64() (f float64, exact bool)

Float64 returns the nearest float64 for the value v, and a bool indicating if the float represents the value exactly.

func (Value) Formatter added in v0.2.0

func (v Value) Formatter(language language.Tag) ValueFormatter

func (*Value) GobDecode added in v0.2.0

func (v *Value) GobDecode(data []byte) error

GobDecode implements the gob.GobDecoder interface.

func (Value) GobEncode added in v0.2.0

func (v Value) GobEncode() ([]byte, error)

GobEncode implements the gob.GobEncoder interface.

func (Value) GormDBDataType

func (v Value) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType returns the datatype that a database should use for the field.

func (Value) GreaterThan added in v0.2.0

func (v Value) GreaterThan(comp Value) bool

GreaterThan returns if the monetary value is greater than another value. If the currency differs between the two values, the result is always false.

func (Value) GreaterThanDetailed added in v0.3.0

func (v Value) GreaterThanDetailed(comp Value) (bool, error)

GreaterThanDetailed returns if the monetary value is greater than another value. If the currency differs between the two values, the result is always false and an error is returned.

func (Value) GreaterThanOrEqual added in v0.2.0

func (v Value) GreaterThanOrEqual(comp Value) bool

GreaterThanOrEqual returns if the monetary value is greater than or equal to another value. If the currency differs between the two values, the result is always false.

func (Value) GreaterThanOrEqualDetailed added in v0.3.0

func (v Value) GreaterThanOrEqualDetailed(comp Value) (bool, error)

GreaterThanOrEqualDetailed returns if the monetary value is greater than or equal to another value. If the currency differs between the two values, the result is always false and an error is returned.

func (Value) InexactFloat64 added in v0.2.0

func (v Value) InexactFloat64() float64

InexactFloat64 returns the nearest float64 for the value v.

func (Value) IsNegative added in v0.2.0

func (v Value) IsNegative() bool

IsNegative returns true when the value is smaller than zero, false otherwise. The currency is ignored.

func (Value) IsPositive added in v0.2.0

func (v Value) IsPositive() bool

IsPositive returns true when the value is greater than zero, false otherwise. The currency is ignored.

func (Value) IsZero added in v0.2.0

func (v Value) IsZero() bool

IsZero returns true when the value is exactly zero. The currency is ignored.

func (Value) LessThan added in v0.2.0

func (v Value) LessThan(comp Value) bool

LessThan returns if the monetary value is less than another value. If the currency differs between the two values, the result is always false.

func (Value) LessThanDetailed added in v0.3.0

func (v Value) LessThanDetailed(comp Value) (bool, error)

LessThanDetailed returns if the monetary value is less than another value. If the currency differs between the two values, the result is always false and an error is returned.

func (Value) LessThanOrEqual added in v0.2.0

func (v Value) LessThanOrEqual(comp Value) bool

LessThanOrEqual returns if the monetary value is less than or equal to another value. If the currency differs between the two values, the result is always false.

func (Value) LessThanOrEqualDetailed added in v0.3.0

func (v Value) LessThanOrEqualDetailed(comp Value) (bool, error)

LessThanOrEqualDetailed returns if the monetary value is less than or equal to another value. If the currency differs between the two values, the result is always false and an error is returned.

func (Value) MarshalBinary added in v0.2.0

func (v Value) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (Value) MarshalJSON

func (v Value) MarshalJSON() ([]byte, error)

MarshalJSON returns the marshaled representation of the object.

func (Value) MarshalText added in v0.2.0

func (v Value) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (Value) Mul added in v0.2.0

func (v Value) Mul(v2 Value) (Value, error)

Mul returns v * v2 as a new value. It will not mutate either v or v2.

In case both values have a currency, this will return an error.

func (Value) MustAdd added in v0.2.0

func (v Value) MustAdd(v2 Value) Value

MustAdd returns v + v2 as a new value. It will not mutate either v or v2.

In case the two values don't use the same currency, this will panic. Use this version if you have already made sure that the currency is equal between both values.

func (Value) MustMul added in v0.2.0

func (v Value) MustMul(v2 Value) Value

MustMul returns v * v2 as a new value. It will not mutate either v or v2.

In case both values have a currency, this will panic.

func (Value) MustSub added in v0.2.0

func (v Value) MustSub(v2 Value) Value

MustSub returns v - v2 as a new value. It will not mutate either v or v2.

In case the two values don't use the same currency, this will panic. Use this version if you have already made sure that the currency is equal between both values.

func (Value) Neg added in v0.2.0

func (v Value) Neg() Value

Neg returns the negative value.

MustFromString("-123.456 ISO4217-EUR").Neg() // Returns "123.456 ISO4217-EUR"
MustFromString("123.456 ISO4217-EUR").Neg()  // Returns "-123.456 ISO4217-EUR"

func (*Value) Scan

func (v *Value) Scan(value interface{}) error

Scan fills the object with data matching the given value from the database.

func (Value) Sign added in v0.2.0

func (v Value) Sign() int

Sign returns:

-1 if v <  0
 0 if v == 0
+1 if v >  0

The currency is ignored.

func (Value) Split added in v0.2.0

func (v Value) Split(n int) ([]Value, error)

Split returns the value of v split into a list of n values. If the value can't be split evenly, the remainder will be distributed round-robin amongst the parts. The smallest unit is determined by the currency of the given value.

MustFromString("-11.11 ISO4217-EUR").Split(3) // Returns the three EUR values `-3.71`, `-3.7`, `-3.7`.
MustFromString("-11.11 ISO4217-VND").Split(3) // Returns an error, as the value can't be split into parts that are multiple of the smallest unit (1).
MustFromString("-1111 ISO4217-VND").Split(3)  // Returns the three VND values `-371`, `-370`, `-370`.
MustFromString("-11.11").Split(3)             // Returns an error, as there is no smallest unit.

func (Value) SplitWithDecimals added in v0.2.0

func (v Value) SplitWithDecimals(n int, decimalPlaces int) ([]Value, error)

SplitWithDecimals returns the value of v split into a list of n values. If the value can't be split evenly, the remainder will be distributed round-robin amongst the parts. The smallest unit that the value is split into is calculated by 10^(-decimalPlaces).

MustFromString("-11.11 ISO4217-EUR").SplitWithDecimals(3, 2) // Returns the three EUR values `-3.71`, `-3.7`, `-3.7`.
MustFromString("-11.11 ISO4217-EUR").SplitWithDecimals(3, 1) // Returns an error, as the value can't be split into parts that are multiple of the smallest unit (0.1).

func (Value) SplitWithSmallestUnit added in v0.2.0

func (v Value) SplitWithSmallestUnit(n int, smallestUnit Value) ([]Value, error)

SplitWithSmallestUnit returns the value of v split into a list of n values. If the value can't be split evenly, the remainder will be distributed round-robin amongst the parts. The resulting values will always be multiple of smallestUnit, if that's not possible an error will be returned.

MustFromString("-11.11").SplitWithSmallestUnit(3, MustFromString("0.01"))                         // Returns the three values `-3.71`, `-3.7`, `-3.7`.
MustFromString("-11.11 ISO4217-EUR").SplitWithSmallestUnit(3, MustFromString("0.01 ISO4217-EUR")) // Returns the three EUR values `-3.71`, `-3.7`, `-3.7`.
MustFromString("-11.11").SplitWithSmallestUnit(3, MustFromString("0.1"))                          // Returns an error, as the value can't be split into parts that are multiple of the smallest unit (0.1).

func (Value) String

func (v Value) String() string

String returns the monetary value as a "Amount UniqueCode" pair. This is locale independent.

func (Value) Sub added in v0.2.0

func (v Value) Sub(v2 Value) (Value, error)

Sub returns v - v2 as a new value. It will not mutate either v or v2.

In case the two values don't use the same currency, this will return an error.

func (*Value) UnmarshalBinary added in v0.2.0

func (v *Value) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

func (*Value) UnmarshalJSON

func (v *Value) UnmarshalJSON(data []byte) error

UnmarshalJSON fills the object with data matching the json representation. This will not be called if the JSON field of this value doesn't exist, therefore old data may persist after unmarshalling.

func (*Value) UnmarshalText added in v0.2.0

func (v *Value) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (Value) Value

func (v Value) Value() (driver.Value, error)

Value implements the valuer interface of databases.

The format that is returned allows to be used with PostgreSQL composite types.

type ValueFormatter added in v0.2.0

type ValueFormatter struct {
	// contains filtered or unexported fields
}

ValueFormatter encapsulates a value and provides formatting capabilities.

func (ValueFormatter) Display added in v0.2.0

func (ValueFormatter) String added in v0.2.0

func (v ValueFormatter) String() string

type ValueFormatterDisplay added in v0.2.0

type ValueFormatterDisplay int
const (
	DisplaySymbol     ValueFormatterDisplay = iota // Formatter will use the currency symbol. E.g. "US$". This is the default.
	DisplayNarrow                                  // Formatter will use the narrow currency symbol. E.g. "$".
	DisplayCode                                    // Formatter will use the currency code. E.g. "USD".
	DisplayUniqueCode                              // Formatter will use the currency's unique code. E.g. "ISO4217-USD".
	DisplayName                                    // Formatter will use the currency name. E.g. "US dollar" or "US dollars".
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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