Documentation
¶
Overview ¶
Package decimal is the Go type of a schema.lidza decimal(p, s) field, a Postgres numeric(p, s) column: an exact decimal number kept as its text, "12.50", never as a float. JSON carries it as a string, so no client parses it into a binary float on the way; pgx reads and writes it as numeric, and sqlc maps numeric columns to it.
Arithmetic goes through math/big: Rat gives the exact value, FromRat rounds a result back to a scale.
total := new(big.Rat).Mul(price.Rat(), big.NewRat(int64(qty), 1)) order.Total = decimal.FromRat(total, 2)
Index ¶
- type Decimal
- func (d Decimal) Cmp(o Decimal) int
- func (d Decimal) Fits(precision, scale int) bool
- func (d Decimal) MarshalJSON() ([]byte, error)
- func (d Decimal) MarshalText() ([]byte, error)
- func (d Decimal) NumericValue() (pgtype.Numeric, error)
- func (d Decimal) Rat() *big.Rat
- func (d *Decimal) Scan(src any) error
- func (d *Decimal) ScanNumeric(n pgtype.Numeric) error
- func (d Decimal) Sign() int
- func (d Decimal) String() string
- func (d *Decimal) UnmarshalJSON(b []byte) error
- func (d *Decimal) UnmarshalText(b []byte) error
- func (d Decimal) Valid() bool
- func (d Decimal) Value() (driver.Value, error)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Decimal ¶
type Decimal string
Decimal is an exact decimal number in plain notation: an optional minus sign, digits, and optionally a point and more digits. The zero value "" is 0. A literal converts directly (Price: "12.50"); text from outside goes through Parse.
func FromRat ¶
FromRat renders r with scale digits after the point, rounding half away from zero as Postgres does.
func Parse ¶
Parse reads a decimal number: "12.50", "-3", "+0.5", or with an exponent, "1.25e3". The result is in plain notation with the sign normalized and redundant leading zeros removed; trailing zeros stay, since they carry the scale ("12.50").
func (Decimal) Cmp ¶
Cmp compares d and o exactly: -1 when d < o, 0 when equal, +1 when d > o. A value that is not a number compares as 0.
func (Decimal) Fits ¶
Fits reports whether d is a number a numeric(precision, scale) column holds without rounding: at most precision-scale digits before the point and scale after it (trailing zeros aside).
func (Decimal) MarshalJSON ¶
MarshalJSON writes the number as a JSON string, "12.50".
func (Decimal) MarshalText ¶
MarshalText and UnmarshalText let a Decimal be a map key or a query parameter.
func (Decimal) NumericValue ¶
NumericValue writes d to a numeric column through pgx.
func (*Decimal) ScanNumeric ¶
ScanNumeric reads a numeric column through pgx.
func (*Decimal) UnmarshalJSON ¶
UnmarshalJSON reads a JSON string ("12.50") or a JSON number (12.5, kept exactly as written).