money

package
v0.0.0-...-d4f462a Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2015 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package money uses a fixed-length guard for precision arithmetic. Implements Un/Marshaller and Scan() method for database columns including null, optimized for decimal(12, 4) fields.

Rounding is done on float64 to int64 by the Rnd() function truncating at values less than (.5 + (1 / Guardf)) or greater than -(.5 + (1 / Guardf)) in the case of negative numbers. The Guard adds four decimal places of protection to rounding. Decimal precision can be changed in the Precision() option function. Precision() hold the places after the decimal place in the active money struct field m.

http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

New()

Creating a new Currency struct:

c := New()

Default values are 10000 for decimals, JSONLocale for Marshal/Unmarshal, Swedish rounding is disabled and i18n.DefaultCurrency (en-US) for number and currency format.

The following options can be set while calling New():

c := New(Swedish(Interval005), Guard(100), Precision(100))

Those values are really optional and even the order they appear ;-). Default settings are:

Precision 10000 which reflects decimal(12,4) database field
Guard 	  10000 which reflects decimal(12,4) database field
Swedish   No rounding

If you need to temporarily set a different option value you can stick to this pattern: http://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html

prev := m.Option(Swedish(Interval005))
defer m.Option(prev)
// do something with the different Swedish rounding

Initial Idea: Copyright (c) 2011 Jad Dittmar https://github.com/Confunctionist/finance

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrOverflow occurs on integer overflow
	ErrOverflow = errors.New("Integer Overflow")

	RoundTo = .5
	//	RoundTo  = .5 + (1 / Guardf)
	RoundToN = RoundTo * -1
)
View Source
var DefaultFormatterCurrency i18n.CurrencyFormatter = i18n.DefaultCurrency

DefaultFormatterCurrency sets the package wide default locale specific currency formatter. This variable can be overridden.

View Source
var DefaultFormatterNumber i18n.NumberFormatter = i18n.DefaultNumber

DefaultFormatterNumber sets the package wide default locale specific number formatter This variable can be overridden.

View Source
var ErrDecodeMissingColon = errors.New("No colon found in JSON array")

ErrDecodeMissingColon can be returned on malformed JSON value when decoding a currency.

Functions

func DefaultGuard

func DefaultGuard(g int) int

DefaultGuard sets the global default guard. A fixed-length guard for precision arithmetic. Returns the successful applied value.

func DefaultPrecision

func DefaultPrecision(p int) int

DefaultPrecision sets the global default decimal precision. 2 decimal places => 10^2; 3 decimal places => 10^3; x decimal places => 10^x Returns the successful applied value.

func DefaultSwedish

func DefaultSwedish(i Interval)

DefaultSwedish sets the global and New() defaults swedish rounding. Errors will be logged. http://en.wikipedia.org/wiki/Swedish_rounding

Types

type Currency

type Currency struct {

	// Valid if false the internal value is NULL
	Valid bool
	// Interval defines how the swedish rounding can be applied.
	Interval Interval
	// contains filtered or unexported fields
}

Currency represents a money aka currency type to avoid rounding errors with floats. Includes options for printing, Swedish rounding, database scanning and JSON en/decoding.

func New

func New(opts ...OptionFunc) Currency

New creates a new empty Currency struct with package default values. Formatter can be overridden after you have created the new type. Implements the interfaces: database.Scanner, driver.Valuer, json.Marshaller, json.Unmarshaller

func (Currency) Abs

func (c Currency) Abs() Currency

Abs returns the absolute value of Currency

func (Currency) Add

func (c Currency) Add(d Currency) Currency

Add adds two Currency types. Returns empty Currency on integer overflow. Errors will be logged and a trace is available when the level for tracing has been set.

func (Currency) Dec

func (c Currency) Dec() int64

Dec returns the decimals

func (Currency) Div

func (c Currency) Div(d Currency) Currency

Div divides one Currency type from another

func (Currency) Ftoa

func (c Currency) Ftoa() []byte

Ftoa converts the internal floating-point number to a byte slice without any applied formatting.

func (Currency) FtoaAppend

func (c Currency) FtoaAppend(dst []byte) []byte

FtoaAppend converts the internal floating-point number to a byte slice without any applied formatting and appends it to dst and returns the extended buffer.

func (Currency) Getf

func (c Currency) Getf() float64

Getf gets the float64 value of money (see Raw() for int64)

func (Currency) Geti

func (c Currency) Geti() int64

Geti gets value of money truncating after decimal precision (see Raw() for no truncation). Rounds always down

func (Currency) Localize

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

Localize for money type representation in a specific locale.

func (Currency) LocalizeWriter

func (c Currency) LocalizeWriter(w io.Writer) (int, error)

LocalizeWriter for money type representation in a specific locale. Returns the number bytes written or an error.

func (Currency) MarshalJSON

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

MarshalJSON generates JSON output depending on the Marshaller.

func (Currency) Mul

func (c Currency) Mul(d Currency) Currency

Mul multiplies two Currency types. Both types must have the same precision.

func (Currency) Mulf

func (c Currency) Mulf(f float64) Currency

Mulf multiplies a Currency with a float to return a money-stored type

func (Currency) Neg

func (c Currency) Neg() Currency

Neg returns the negative value of Currency

func (Currency) Number

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

Number prints the currency without any locale specific formatting. E.g. useful in JavaScript.

func (Currency) NumberWriter

func (c Currency) NumberWriter(w io.Writer) (int, error)

NumberWriter prints the currency as a locale specific formatted number. Returns the number bytes written or an error.

func (*Currency) Option

func (c *Currency) Option(opts ...OptionFunc) (previous OptionFunc)

Options besides New() also Option() can apply options to the current struct. It returns the last set option. More info about the returned function: http://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html

func (*Currency) ParseFloat

func (c *Currency) ParseFloat(s string) error

ParseFloat transforms a string float value into a real float64 value and sets it. Current value will be overridden. Returns a logged error.

func (Currency) Pow

func (c Currency) Pow(f float64) Currency

Pow is the power of Currency

func (Currency) Precision

func (c Currency) Precision() int

Precision returns the amount of decimal digits

func (Currency) Raw

func (c Currency) Raw() int64

Raw returns in int64 the value of Currency (also see Geti(), See Getf() for float64)

func (*Currency) Scan

func (c *Currency) Scan(src interface{}) error

Scan scans a value into the Currency struct. Returns an error on data loss. Errors will be logged. Initial default settings are the guard and precision value.

func (Currency) Set

func (c Currency) Set(i int64) Currency

Set sets the raw Currency field m

func (Currency) Setf

func (c Currency) Setf(f float64) Currency

Setf sets a float64 into a Currency type for precision calculations

func (Currency) Sign

func (c Currency) Sign() int

Sign returns:

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

func (Currency) String

func (c Currency) String() string

String for money type representation in a specific locale.

func (Currency) Sub

func (c Currency) Sub(d Currency) Currency

Sub subtracts one Currency type from another. Returns empty Currency on integer overflow. Errors will be logged and a trace is available when the level for tracing has been set.

func (Currency) Swedish

func (c Currency) Swedish(opts ...OptionFunc) Currency

Swedish applies the Swedish rounding. You may set the usual options.

func (Currency) Symbol

func (c Currency) Symbol() []byte

Symbol returns the currency symbol: €, $, AU$, CHF depending on the formatter.

func (*Currency) UnmarshalJSON

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

UnmarshalJSON reads JSON and fills the currency struct depending on the Unmarshaller.

func (*Currency) Value

func (c *Currency) Value() (driver.Value, error)

Value implements the SQL driver Valuer interface.

type Interval

type Interval uint8

Interval defines the type for the Swedish rounding.

const (
	// Interval000 no swedish rounding (default)
	Interval000 Interval = iota
	// Interval005 rounding with 0.05 intervals
	Interval005
	// Interval010 rounding with 0.10 intervals
	Interval010
	// Interval015 same as Interval010 except that 5 will be rounded down.
	// 0.45 => 0.40 or 0.46 => 0.50
	// Special case for New Zealand (a must visit!), it is up to the business
	// to decide if they will round 5¢ intervals up or down. The majority of
	// retailers follow government advice and round it down. Use then Interval015.
	// otherwise use Interval010.
	Interval015
	// Interval025 rounding with 0.25 intervals
	Interval025
	// Interval050 rounding with 0.50 intervals
	Interval050
	// Interval100 rounding with 1.00 intervals
	Interval100
)

Interval* constants http://en.wikipedia.org/wiki/Swedish_rounding

type JSONMarshaller

type JSONMarshaller interface {
	// MarshalJSON encodes the currency
	MarshalJSON(*Currency) ([]byte, error)
}

JSONMarshaller interface for JSON encoding

var DefaultJSONEncode JSONMarshaller = NewJSONEncoder()

DefaultJSONEncode is JSONLocale

func NewJSONEncoder

func NewJSONEncoder(jts ...JSONType) JSONMarshaller

NewJSONEncoder creates a new encoder depending on the type. Accepts either zero or one argument. Default encoder is JSONLocale

type JSONType

type JSONType uint8

JSONType defines the type of the marshaller/unmarshaller

const (
	// JSONNumber encodes/decodes a currency as a number string to directly use
	// in e.g. JavaScript
	JSONNumber JSONType = 1 << iota
	// JSONLocale encodes/decodes a currency according to its locale format.
	// Decoding: Considers the locale if the currency symbol is valid.
	JSONLocale
	// JSONExtended encodes/decodes a currency into a JSON array:
	// [1234.56, "€", "1.234,56 €"].
	// Decoding: Considers the locale if the currency symbol is valid.
	JSONExtended
)

func (JSONType) MarshalJSON

func (t JSONType) MarshalJSON(c *Currency) ([]byte, error)

MarshalJSON encodes a currency to JSON bytes according to the defined JSONType

func (JSONType) UnmarshalJSON

func (t JSONType) UnmarshalJSON(c *Currency, b []byte) error

UnmarshalJSON decodes three different currency representations into a currency struct.

type JSONUnmarshaller

type JSONUnmarshaller interface {
	// UnmarshalJSON reads the bytes and decodes them into the currency
	UnmarshalJSON(*Currency, []byte) error
}

JSONUnmarshaller interface for JSON decoding

var DefaultJSONDecode JSONUnmarshaller = NewJSONDecoder()

DefaultJSONDecode is JSONLocale

func NewJSONDecoder

func NewJSONDecoder(jts ...JSONType) JSONUnmarshaller

NewJSONDecoder creates a new decoder depending on the type. Accepts either zero or one argument. Default decoder is JSONLocale

type OptionFunc

type OptionFunc func(*Currency) OptionFunc

OptionFunc used to apply options to the Currency struct

func CashRounding

func CashRounding(rounding int) OptionFunc

CashRounding same as Swedish() option function, but: Rounding increment, in units of 10-digits. The default is 0, which means no rounding is to be done. Therefore, rounding=0 and rounding=1 have identical behavior. Thus with fraction digits of 2 and rounding increment of 5, numeric values are rounded to the nearest 0.05 units in formatting. With fraction digits of 0 and rounding increment of 50, numeric values are rounded to the nearest 50. Possible values: 5, 10, 15, 25, 50, 100

func FormatCurrency

func FormatCurrency(cf i18n.CurrencyFormatter) OptionFunc

FormatCurrency to allow language and format specific outputs in a currency format

func FormatNumber

func FormatNumber(nf i18n.NumberFormatter) OptionFunc

FormatNumber to allow language and format specific outputs in a number format

func Guard

func Guard(g int) OptionFunc

Guard sets the guard

func JSONMarshal

func JSONMarshal(m JSONMarshaller) OptionFunc

JSONMarshal sets a custom JSON Marshaller. Default is JSONLocale.

func JSONUnmarshal

func JSONUnmarshal(um JSONUnmarshaller) OptionFunc

JSONUnmarshal sets a custom JSON Unmmarshaller. Default is JSONLocale.

func Precision

func Precision(p int) OptionFunc

Precision sets the precision. 2 decimal places => 10^2; 3 decimal places => 10^3; x decimal places => 10^x If not a decimal power then falls back to the default value.

func Swedish

func Swedish(i Interval) OptionFunc

Swedish sets the Swedish rounding http://en.wikipedia.org/wiki/Swedish_rounding Errors will be logged

Jump to

Keyboard shortcuts

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