money

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2019 License: MIT Imports: 12 Imported by: 1

README

money

Documentation

Index

Constants

View Source
const (
	// SignPositive is the number returned by Sign() when a decimal is positive
	SignPositive = 1
	// SignNeutral is the number returned by Sign() when a decimal is neutral (0)
	SignNeutral = 0
	// SignNegative is the number returned by Sign() when a decimal is negative
	SignNegative = -1
)

Variables

View Source
var (
	// ErrInvalidCurrency indicates that the string is not a valid currency as defined by ISO 4217
	ErrInvalidCurrency = errors.New("invalid currency")
	// ErrUnsupportedCurrency indicates that the currency is not supported
	ErrUnsupportedCurrency = errors.New("unsupported currency")
)
View Source
var (
	// FormatterNarrowSymbol usess narrow symbols. Overrides Symbol, if present.
	FormatterNarrowSymbol = currency.NarrowSymbol

	// FormatterSymbol uses symbols instead of ISO codes, when available.
	FormatterSymbol = currency.Symbol

	// FormatterISO uses ISO code as symbol.
	FormatterISO = currency.ISO
)
View Source
var (
	// ErrInvalidDecimal indicates that the string is not a valid decimal
	ErrInvalidDecimal = errors.New("invalid decimal")
)

Functions

func RegisterUnoficialCurrency

func RegisterUnoficialCurrency(code string)

RegisterUnoficialCurrency registers a currency code that is not a valid ISO 4217 currency code.

This can be used for crypto currency codes, such as ETH, DAI, USDC, ...

Types

type Currency

type Currency string

Currency is represented in code as defined by the ISO 4217 format.

Examples:

  • Swiss franc - CHF
  • United States dollar - USD
  • Euro - EUR
  • Polish złoty - PLN
  • Bitcoin - XBT

func MustParseCurrency

func MustParseCurrency(s string) Currency

MustParseCurrency is like ParseCurency, but panics if the given currency unit cannot be parsed. It simplifies safe initialisation of Currency values.

func ParseCurrency

func ParseCurrency(s string) (Currency, error)

ParseCurrency parses a 3-letter ISO 4217 currency code. It returns an error if it is not well-formed or not a recognised currency code.

Examples:

  • CHF
  • XBT

func (*Currency) GobDecode

func (c *Currency) GobDecode(data []byte) error

GobDecode implements the gob.GobDecoder interface for gob serialization.

func (Currency) GobEncode

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

GobEncode implements the gob.GobEncoder interface for gob serialization.

func (Currency) MarshalJSON

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

MarshalJSON implements the json.Marshaler interface.

func (Currency) RoundUnit

func (c Currency) RoundUnit(kind RoundingKind) Decimal

RoundUnit returns a rounding unit for the given kind

func (Currency) Scale

func (c Currency) Scale() int

Scale returns the standard currency scale

func (Currency) String

func (c Currency) String() string

String returns the ISO 4217 representation of a currency (e.g. CHF)

func (*Currency) UnmarshalJSON

func (c *Currency) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (Currency) Validate

func (c Currency) Validate() error

Validate returns whether the currency is valid

type CurrencyFormatter

type CurrencyFormatter = currency.Formatter

CurrencyFormatter decorates a given number with formatting options.

type Decimal

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

Decimal represents a fixed-point decimal. It is immutable. number = value * 10 ^ exp

func MaxDecimal

func MaxDecimal(first Decimal, rest ...Decimal) Decimal

MaxDecimal returns the largest Decimal that was passed in the arguments.

To call this function with an array, you must do:

Max(arr[0], arr[1:]...)

This makes it harder to accidentally call Max with 0 arguments.

func MinDecimal

func MinDecimal(first Decimal, rest ...Decimal) Decimal

MinDecimal returns the smallest Decimal that was passed in the arguments.

To call this function with an array, you must do:

Min(arr[0], arr[1:]...)

This makes it harder to accidentally call Min with 0 arguments.

func MustParseDecimal

func MustParseDecimal(value string) Decimal

func NewDecimal

func NewDecimal(value float64) (Decimal, error)

NewDecimal creates a Decimal from a float

Example:

NewFromFloat(123.45678901234567).String() // output: "123.4567890123456"
NewFromFloat(.00000000000000001).String() // output: "0.00000000000000001"

NOTE: errors occur on NaN, +/-inf

func ParseDecimal

func ParseDecimal(value string) (Decimal, error)

ParseDecimal parses the value which must contain a text representation of a floating-point number. The number of integers after the radix point (fraction) determines the rounding precision.

e.g. 120.0 	-> Precision 1
e.g. 123.456	-> Precision 3

func Pow10 added in v1.0.0

func Pow10(d Decimal) Decimal

Pow10 returns 10**d, the base-10 exponential of d.

func Round

func Round(x Decimal, unit Decimal, mode RoundingMode) Decimal

Round rounds the given amount from the given unit

func (Decimal) Abs

func (d Decimal) Abs() Decimal

Abs returns the absolute value of the decimal.

func (Decimal) Add

func (d Decimal) Add(d2 Decimal) Decimal

Add returns d + d2.

func (Decimal) Ceil

func (d Decimal) Ceil() Decimal

Ceil returns the nearest integer value greater than or equal to d.

func (Decimal) Cmp

func (d Decimal) Cmp(d2 Decimal) int

Cmp compares the numbers represented by d and d2 and returns:

-1 if d <  d2
 0 if d == d2
+1 if d >  d2

func (Decimal) Coefficient

func (d Decimal) Coefficient() big.Int

Coefficient returns the coefficient of the decimal. It is scaled by 10^Exponent()

func (Decimal) DeepCopy

func (d Decimal) DeepCopy(dst interface{}) error

func (Decimal) Div

func (d Decimal) Div(d2 Decimal) Decimal

Div returns d / d2. If it doesn't divide exactly, the result will have DivisionPrecision digits after the decimal point.

func (Decimal) Equal

func (d Decimal) Equal(d2 Decimal) bool

Equal returns whether the numbers represented by d and d2 are equal.

func (Decimal) Exponent

func (d Decimal) Exponent() int32

Exponent returns the exponent, or scale component of the decimal.

func (Decimal) Float64

func (d Decimal) Float64() float64

Float64 returns the nearest float64 value for d

func (Decimal) Floor

func (d Decimal) Floor() Decimal

Floor returns the nearest integer value less than or equal to d.

func (*Decimal) Formatter

func (d *Decimal) Formatter(scale ...int) number.Formatter

Formatter returns a language/currency-specific formatter for a floating point decimal

func (*Decimal) GobDecode

func (d *Decimal) GobDecode(data []byte) error

GobDecode implements the gob.GobDecoder interface for gob serialization.

func (Decimal) GobEncode

func (d Decimal) GobEncode() ([]byte, error)

GobEncode implements the gob.GobEncoder interface for gob serialization.

func (Decimal) IntPart

func (d Decimal) IntPart() int64

IntPart returns the integer component of the decimal.

func (Decimal) IsZero

func (d Decimal) IsZero() bool

IsZero reports whether d represents the zero value

func (Decimal) MarshalBinary

func (d Decimal) MarshalBinary() (data []byte, err error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (Decimal) MarshalJSON

func (d Decimal) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (Decimal) MarshalText

func (d Decimal) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface for XML serialization.

func (Decimal) Mod

func (d Decimal) Mod(d2 Decimal) Decimal

Mod returns d % d2.

func (Decimal) Mul

func (d Decimal) Mul(d2 Decimal) Decimal

Mul returns d * d2.

func (Decimal) Neg

func (d Decimal) Neg() Decimal

Neg returns -d.

func (*Decimal) PercentFormatter

func (d *Decimal) PercentFormatter() number.Formatter

PercentFormatter returns a language-specific formatter for a percent

func (Decimal) Pow

func (d Decimal) Pow(d2 Decimal) Decimal

Pow returns d to the power d2

func (Decimal) Rat

func (d Decimal) Rat() *big.Rat

Rat returns a rational number representation of the decimal.

func (Decimal) Round

func (d Decimal) Round(places int32) Decimal

Round rounds the decimal to places decimal places. If places < 0, it will round the integer part to the nearest 10^(-places).

Example:

NewFromFloat(5.45).Round(1).String() // output: "5.5"
NewFromFloat(545).Round(-1).String() // output: "550"

func (Decimal) RoundDown

func (d Decimal) RoundDown(precision int32) Decimal

RoundDown rounds the decimal down to the given precision instead of to the nearest even

e.g.:
3.1416 -> f(3) = 3.142
3.1416 -> f(2) = 3.15

func (Decimal) RoundNearest

func (d Decimal) RoundNearest(unit Decimal) Decimal

RoundNearest rounds the decimal to the nearest unit

e.g.:
3.1216 -> f(0.05) = 3.10
3.1416 -> f(0.05) = 3.15

func (Decimal) RoundUp

func (d Decimal) RoundUp(precision int32) Decimal

RoundUp rounds the decimal up to the given precision instead of to the nearest even

e.g.:
3.1416 -> f(3) = 3.142
3.1416 -> f(2) = 3.15

func (Decimal) Sign

func (d Decimal) Sign() int

Sign returns:

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

func (Decimal) String

func (d Decimal) String() string

func (Decimal) Sub

func (d Decimal) Sub(d2 Decimal) Decimal

Sub returns d - d2.

func (Decimal) Truncate

func (d Decimal) Truncate(precision int32) Decimal

Truncate truncates off digits from the number, without rounding.

NOTE: precision is the last digit that will not be truncated (must be >= 0).

Example:

decimal.NewFromString("123.456").Truncate(2).String() // "123.45"

func (*Decimal) UnmarshalBinary

func (d *Decimal) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. As a string representation is already used when encoding to text, this method stores that string as []byte

func (*Decimal) UnmarshalJSON

func (d *Decimal) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Decimal) UnmarshalText

func (d *Decimal) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for XML deserialization.

func (Decimal) Validate

func (d Decimal) Validate() error

Validate returns whether the currency is valid

type DecimalFormatter

type DecimalFormatter struct {
	CurrencyFormater CurrencyFormatter
	Currency         Currency
	Rounding         RoundingKind
}

DecimalFormatter formats Decimal to its string representation

func (*DecimalFormatter) Wrap

func (f *DecimalFormatter) Wrap(x *Decimal) fmt.Formatter

Wrap decorates x with the formating preferences

type Formatter

type Formatter struct {
	CurrencyFormater CurrencyFormatter
	Rounding         RoundingKind
}

Formatter formats Money to its string representation

func (*Formatter) Wrap

func (f *Formatter) Wrap(x *Money) fmt.Formatter

Wrap decorates x with the formating preferences

type Money

type Money struct {
	Amount   Decimal  `json:"amount"`
	Currency Currency `json:"currency"`
}

Money represents an amount of money for a currency

Money is any item or verifiable record that is generally accepted as payment for goods and services and repayment of debts

func Add

func Add(x, y *Money) *Money

Add returns an amount set to the rounded sum x+y. The precision is set to the larger of x's or y's precision before the operation. Rounding is performed according to the default rounding mode

func Div

func Div(x, y *Money) *Money

Div sets z to the rounded quotient x/y and returns z. Precision, rounding, and accuracy reporting are as for Add. Quo panics with ErrNaN if both operands are zero or infinities.

func Mul

func Mul(x, y *Money) *Money

Mul sets z to the rounded product x*y and returns z. Precision, rounding, and accuracy reporting are as for Add. Mul panics with ErrNaN if one operand is zero and the other operand an infinity.

func MustParse

func MustParse(amount, currency string) *Money

MustParse is like Parse, but panics if the given amount or currency cannot be parsed. It simplifies safe initialisation of Money values.

func Parse

func Parse(amount, currency string) (*Money, error)

Parse parses amount which must contain a text representation of a floating-point number. The number of integers after the radix point (fraction) determines the mantissa precision.

e.g. 120.0 	-> Precision 1
e.g. 123.456	-> Precision 3

It also validates the currency, which must represented in code as defined by the ISO 4217 format.

e.g. CHF 		-> Swiss franc

func Sub

func Sub(x, y *Money) *Money

Sub returns an amount set to the rounded difference x-y. Precision, rounding, and accuracy reporting are as for Add. Sub panics with ErrNaN if x and y are infinities with equal signs.

func (*Money) Equal

func (x *Money) Equal(y *Money) bool

Equal tests whether y equal x. When the currency is different, it will always return false. Currency conversion is currently not supported.

func (*Money) Validate

func (x *Money) Validate() error

Validate tests that both the decimal and the currency are valid

type RoundingKind

type RoundingKind string

RoundingKind defines a rounding standard for currencies

var (
	// RoundingStandard defines standard rounding and formatting for currencies.
	RoundingStandard RoundingKind = "standard"

	// RoundingCash defines rounding and formatting standards for cash
	// transactions.
	RoundingCash RoundingKind = "cash"

	// RoundingAccounting defines rounding and formatting standards for
	// accounting.
	RoundingAccounting RoundingKind = "accounting"
)

type RoundingMode

type RoundingMode string

RoundingMode defines the rounding Mode to apply

const (
	// Down rounds down to the previous increment
	// e.g. decimal: 1.49 increment: 0.1 result: 1.4
	RoundDown RoundingMode = "down"
	// Up rounds up to the next increment
	// e.g. decimal: 1.41 increment: 0.1 result: 1.5
	RoundUp RoundingMode = "up"
	// ToNearest rounds to the nearest increment
	// e.g. decimal: 1.45 increment: 0.1 result: 1.5
	RoundToNearest RoundingMode = "to_nearest"
)

Jump to

Keyboard shortcuts

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