Documentation
¶
Overview ¶
Package money holds exact amounts of US dollars. Nothing in it rounds: rounding is a display decision, made where an amount is shown.
Index ¶
- Constants
- Variables
- type USD
- func (u USD) Add(v USD) USD
- func (u USD) Cmp(v USD) int
- func (u USD) Equal(v USD) bool
- func (u USD) IsNegative() bool
- func (u USD) IsPositive() bool
- func (u USD) IsZero() bool
- func (u USD) MarshalJSON() ([]byte, error)
- func (u USD) Mul(n int64) USD
- func (u USD) PerMillion(n int64) USD
- func (u USD) Ratio(of USD) float64
- func (u USD) String() string
- func (u USD) Sub(v USD) USD
- func (u *USD) UnmarshalJSON(b []byte) error
Constants ¶
const MaxPlaces = 18
MaxPlaces is the most decimal places Parse and ParseLenient accept.
Variables ¶
var ErrInvalid = errors.New("money: invalid amount")
ErrInvalid reports a string that is not an amount.
Functions ¶
This section is empty.
Types ¶
type USD ¶
type USD struct {
// contains filtered or unexported fields
}
USD is an exact decimal amount of US dollars. The zero value is $0.
An amount read by Parse or ParseLenient carries at most MaxPlaces decimal places, the most a Postgres NUMERIC(38,18) column keeps, so no store rounds one silently. Computed amounts are rounded to MaxPlaces in PerMillion, the only operation that adds places.
Compare amounts with Equal or IsZero, never ==: two equal amounts can differ in representation.
var Zero USD
Zero is $0.
func Parse ¶
Parse reads a plain decimal such as "0.15", ".5" or "-3". It refuses exponents, NaN, Inf, a leading plus sign, separators and spaces, so an amount someone typed is read the way they typed it.
func ParseLenient ¶
ParseLenient also accepts exponent notation ("1.50E-7"). It exists for values read back from a database or an old JSON document that prints decimals that way. The result is still exact.
func (USD) IsNegative ¶
IsNegative reports whether u is less than $0.
func (USD) IsPositive ¶
IsPositive reports whether u is more than $0.
func (USD) MarshalJSON ¶
MarshalJSON writes the amount as a JSON string, so no reader can turn it into a float on the way in.
func (USD) PerMillion ¶
PerMillion is the cost of n units at u per million units: u × n / 10⁶, rounded to MaxPlaces decimal places, half away from zero. It is the one operation that adds decimal places, so it is where the bound is kept: an amount the library computes is always one every store can hold and read.
func (USD) Ratio ¶
Ratio is u divided by of, as a float64 for display (a percentage on a dashboard, a hook argument). It is never used to compute money. It is 0 when of is zero.
func (USD) String ¶
String is the exact amount in plain decimal notation with no trailing zeros: "0.15", "1284.370219", "0".
func (*USD) UnmarshalJSON ¶
UnmarshalJSON reads a JSON string strictly, a bare JSON number leniently and exactly from its text (budgets were stored as numbers before amounts were strings), and treats null as "leave the value alone".