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 ¶
- Variables
- func DefaultGuard(g int) int
- func DefaultPrecision(p int) int
- func DefaultSwedish(i Interval)
- type Currency
- func (c Currency) Abs() Currency
- func (c Currency) Add(d Currency) Currency
- func (c Currency) Dec() int64
- func (c Currency) Div(d Currency) Currency
- func (c Currency) Ftoa() []byte
- func (c Currency) FtoaAppend(dst []byte) []byte
- func (c Currency) Getf() float64
- func (c Currency) Geti() int64
- func (c Currency) Localize() ([]byte, error)
- func (c Currency) LocalizeWriter(w io.Writer) (int, error)
- func (c Currency) MarshalJSON() ([]byte, error)
- func (c Currency) Mul(d Currency) Currency
- func (c Currency) Mulf(f float64) Currency
- func (c Currency) Neg() Currency
- func (c Currency) Number() ([]byte, error)
- func (c Currency) NumberWriter(w io.Writer) (int, error)
- func (c *Currency) Option(opts ...OptionFunc) (previous OptionFunc)
- func (c *Currency) ParseFloat(s string) error
- func (c Currency) Pow(f float64) Currency
- func (c Currency) Precision() int
- func (c Currency) Raw() int64
- func (c *Currency) Scan(src interface{}) error
- func (c Currency) Set(i int64) Currency
- func (c Currency) Setf(f float64) Currency
- func (c Currency) Sign() int
- func (c Currency) String() string
- func (c Currency) Sub(d Currency) Currency
- func (c Currency) Swedish(opts ...OptionFunc) Currency
- func (c Currency) Symbol() []byte
- func (c *Currency) UnmarshalJSON(src []byte) error
- func (c *Currency) Value() (driver.Value, error)
- type Interval
- type JSONMarshaller
- type JSONType
- type JSONUnmarshaller
- type OptionFunc
- func CashRounding(rounding int) OptionFunc
- func FormatCurrency(cf i18n.CurrencyFormatter) OptionFunc
- func FormatNumber(nf i18n.NumberFormatter) OptionFunc
- func Guard(g int) OptionFunc
- func JSONMarshal(m JSONMarshaller) OptionFunc
- func JSONUnmarshal(um JSONUnmarshaller) OptionFunc
- func Precision(p int) OptionFunc
- func Swedish(i Interval) OptionFunc
Constants ¶
This section is empty.
Variables ¶
var ( // ErrOverflow occurs on integer overflow ErrOverflow = errors.New("Integer Overflow") RoundTo = .5 // RoundTo = .5 + (1 / Guardf) RoundToN = RoundTo * -1 )
var DefaultFormatterCurrency i18n.CurrencyFormatter = i18n.DefaultCurrency
DefaultFormatterCurrency sets the package wide default locale specific currency formatter. This variable can be overridden.
var DefaultFormatterNumber i18n.NumberFormatter = i18n.DefaultNumber
DefaultFormatterNumber sets the package wide default locale specific number formatter This variable can be overridden.
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 ¶
DefaultGuard sets the global default guard. A fixed-length guard for precision arithmetic. Returns the successful applied value.
func DefaultPrecision ¶
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) Add ¶
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) Ftoa ¶
Ftoa converts the internal floating-point number to a byte slice without any applied formatting.
func (Currency) FtoaAppend ¶
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) Geti ¶
Geti gets value of money truncating after decimal precision (see Raw() for no truncation). Rounds always down
func (Currency) LocalizeWriter ¶
LocalizeWriter for money type representation in a specific locale. Returns the number bytes written or an error.
func (Currency) MarshalJSON ¶
MarshalJSON generates JSON output depending on the Marshaller.
func (Currency) Number ¶
Number prints the currency without any locale specific formatting. E.g. useful in JavaScript.
func (Currency) NumberWriter ¶
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 ¶
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) Raw ¶
Raw returns in int64 the value of Currency (also see Geti(), See Getf() for float64)
func (*Currency) Scan ¶
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) Sub ¶
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 ¶
Symbol returns the currency symbol: €, $, AU$, CHF depending on the formatter.
func (*Currency) UnmarshalJSON ¶
UnmarshalJSON reads JSON and fills the currency struct depending on the Unmarshaller.
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 ¶
MarshalJSON encodes a currency to JSON bytes according to the defined JSONType
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 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