decimal
Exact decimal numbers for money and accounting, with none of the rounding error of floating point.
import decimal
In f64, 0.1 + 0.2 is not exactly 0.3. For science and graphics that tiny error does not matter; for money it does, because a lost cent in the accounts is not acceptable. The decimal package keeps a number as a bigint and a scale, the count of digits after the point, so 10.05 is 1005 with scale 2 and no error can creep in. Use it for prices, invoices, balances, tax and interest. Use f64 and math for measurements and statistics, and plain i64 cents when every amount has the same two places and never exceeds about 92 quadrillion.
Addition, subtraction and multiplication are always exact. The scale of a sum is the larger of the two, and the scale of a product is the two added together. Division may not terminate, as one third does not, so Div takes the number of places you want and a Rounding method. Seven methods are offered; accounting usually wants HalfEven, and customer-facing totals often HalfUp.
What people get wrong:
- Letting the scale grow. Each
Muladds the scales together, so a balance multiplied by a rate every month carries more digits each time. Round to cents after every step that a statement shows. - Expecting school rounding from the formatters.
ToStrFixed,FormatGrouped,RoundandPercentround half to even, so 2.345 shows as 2.34. CallRoundHalfUpfirst when you want 2.35. - Dividing by zero.
Div,DivRoundandDivIntreturn 0 instead of stopping the program, so check the divisor yourself. - Copying with
=. ADecholds abigint.Int, sob := ashares its digits; useClonefor an independent copy, and free each number once.
Why not f64?
Adding 0.1 ten times in f64 gives 0.9999999999999999, because 0.1 has no exact binary form. The same loop with Dec gives exactly 1.0. Build amounts from text with Parse or from whole cents with FromScaled; FromFloat works when you already have an f64, as long as you say how many places it should keep.
import decimal
func main:
mut f := 0.0
repeat 10:
f += 0.1
end
println "f64 sum of ten 0.1:", f, f == 1.0
mut d := decimal.Zero()
tenth := decimal.FromScaled(1, 1)
repeat 10:
d = decimal.Add(d, tenth)
end
println "decimal sum of ten 0.1:", decimal.ToStr(d), decimal.Equals(d, decimal.FromInt(1))
price := decimal.FromFloat(19.99, 2)
println "19.99 from f64:", decimal.ToStr(price)
println "times 3:", decimal.ToStr(decimal.MulInt(price, 3))
endAn invoice with discount and tax
Prices usually come from a database or a form as text, so Parse is the natural start. MulInt multiplies by a quantity without any rounding, and Percent takes a percentage and rounds the result to the places you ask for, half to even. Print with ToStrFixed so that 12 shows as 12.00, or with FormatGrouped for thousands separators.
import decimal
struct Line:
pub name: str = ""
pub price: str = ""
pub qty: int = 0
end
func main:
mut lines := Vector {} as Vector<Line>
defer lines.Free()
lines.Push(Line { name = "Notebook", price = "4.75", qty = 3 })
lines.Push(Line { name = "Pen", price = "1.20", qty = 10 })
lines.Push(Line { name = "Backpack", price = "39.90", qty = 1 })
mut subtotal := decimal.Zero()
each l in lines:
mut ok := false
unit := decimal.Parse(l.price, ok)
amount := decimal.MulInt(unit, l.qty as i64)
println l.name, l.qty, "x", decimal.ToStrFixed(unit, 2), "=", decimal.ToStrFixed(amount, 2)
subtotal = decimal.Add(subtotal, amount)
end
discount := decimal.Percent(subtotal, decimal.FromInt(5), 2)
taxable := decimal.Sub(subtotal, discount)
tax := decimal.Percent(taxable, decimal.FromScaled(95, 1), 2)
total := decimal.Add(taxable, tax)
println "subtotal", decimal.ToStrFixed(subtotal, 2)
println "discount 5%", decimal.ToStrFixed(discount, 2)
println "tax 9.5%", decimal.ToStrFixed(tax, 2)
println "total", decimal.FormatGrouped(total, 2, ",", ".")
endRound once per step that a real invoice shows (the discount, the tax), not at the very end only. Customers and tax offices check each printed line, so each line must already be in cents. The example does not free its numbers to stay short; a long-running server should Free each one, as the split example does.
Interest and the cost of rounding
A bank pays interest in whole cents every year, and those rounded cents then earn interest themselves. The example runs five years with yearly rounding and compares the result with the exact formula: the difference is one cent. Div and DivInt always ask for the number of places and a Rounding method, because a division such as one twelfth has no end.
import decimal
func main:
mut balance := decimal.FromInt(10000)
rate := decimal.FromScaled(15, 3)
one := decimal.FromInt(1)
repeat 1 to 5 in year:
interest := decimal.Round(decimal.Mul(balance, rate), 2)
balance = decimal.Add(balance, interest)
println "year", year, "interest", decimal.ToStrFixed(interest, 2), "balance", decimal.FormatGrouped(balance, 2, ",", ".")
end
factor := decimal.Pow(decimal.Add(one, rate), 5)
exact := decimal.Mul(decimal.FromInt(10000), factor)
println "without yearly rounding", decimal.ToStr(exact)
println "rounded", decimal.ToStrFixed(decimal.Round(exact, 2), 2)
monthly := decimal.DivInt(balance, 12, 2, decimal.Rounding.Down)
println "a twelfth, rounded down", decimal.ToStrFixed(monthly, 2)
endSplitting a bill without losing a cent
Dividing 100.00 by 3 and rounding gives 33.33 three times, which adds up to 99.99. Split gives the missing cent to the first share, so the shares always add up to the original amount. Allocate does the same for shares in a ratio, such as profit split between partners.
import decimal
func show(label: str, parts: Vector<decimal.Dec>):
mut line := label
each p in parts:
line = line + " " + decimal.ToStrFixed(p, 2)
end
total := decimal.Sum(parts)
println line, "| total", decimal.ToStrFixed(total, 2)
end
func main:
bill := decimal.FromScaled(10000, 2)
mut naive := decimal.DivInt(bill, 3, 2, decimal.Rounding.HalfEven)
println "100.00 / 3 rounded:", decimal.ToStrFixed(naive, 2), "x 3 =", decimal.ToStrFixed(decimal.MulInt(naive, 3), 2)
naive.Free()
mut shares := decimal.Split(bill, 3)
show("split in 3:", shares)
decimal.FreeAll(shares)
mut ratios := Vector {} as Vector<i64>
defer ratios.Free()
ratios.Push(50)
ratios.Push(30)
ratios.Push(20)
profit := decimal.FromScaled(123457, 2)
mut parts := decimal.Allocate(profit, ratios)
show("50/30/20 of 1234.57:", parts)
decimal.FreeAll(parts)
endThe leftover smallest units go to the first shares, one each, in both functions; Allocate does not look at which share lost the most to rounding. Split with fewer than one share, and Allocate with no ratios, a negative ratio or ratios that add up to zero, return an empty vector. Both return a new vector of numbers; free it with FreeAll, which releases every number and the vector.
What Parse accepts
Parse skips spaces around the number, accepts a sign, Persian digits, underscores between digits and scientific notation. It refuses a comma as the decimal separator and the Persian separator ٫: replace either with a dot before parsing if your users type them. ParseOr returns zero on failure, which suits optional fields but hides typing mistakes.
import decimal
func main:
inputs := ["1250.50", " -3.75 ", "1_000_000", "۱۲۳.۴۵", "۱۲۳٫۴۵", "2.5e3", "12,50", "abc", ""]
each s in inputs:
mut ok := false
d := decimal.Parse(s, ok)
if ok:
println "[" + s + "]", "->", decimal.ToStr(d), "scale", decimal.Scale(d)
else:
println "[" + s + "]", "-> not a number"
end
end
println decimal.ToStr(decimal.ParseOr("oops"))
endScientific notation can lower the scale: 2.5e3 becomes 2500 with scale 0, and 1.50e1 becomes 15.0.
Rounding, growing scales and zero
The three surprises from the list above, in one program. The price is a typical half-cent case, the repeated Mul is a monthly rate applied four times, and the zero divisor is a team with no members.
import decimal
func main:
mut ok := false
price := decimal.Parse("2.345", ok)
println "ToStrFixed rounds half to even:", decimal.ToStrFixed(price, 2)
println "RoundHalfUp first:", decimal.ToStrFixed(decimal.RoundHalfUp(price, 2), 2)
rate := decimal.Parse("1.075", ok)
mut grown := decimal.Mul(price, rate)
println "Mul adds the scales:", decimal.ToStr(grown), "scale", decimal.Scale(grown)
repeat 3:
grown = decimal.Mul(grown, rate)
end
println "three more times:", decimal.ToStr(grown), "scale", decimal.Scale(grown)
println "rounded to cents:", decimal.ToStr(decimal.Round(grown, 2))
staff := decimal.Zero()
println "shared among zero staff:", decimal.ToStr(decimal.DivRound(price, staff, 2))
if decimal.IsZero(staff):
println "check the divisor before you divide"
end
endFromFloat has a limit of its own: it multiplies the f64 by ten for each place and converts to i64, so a value times 10scale must stay below about 9.2 × 1018. For large amounts, parse text instead.
| Job | Use |
|---|---|
| An amount from text | Parse |
| An amount from whole cents | FromScaled(cents, 2) |
| Price times quantity | MulInt |
| A discount or a tax rate | Percent |
| Round to cents | Round (half to even) or RoundHalfUp |
| Divide fairly | Split, Allocate |
| Show to a user | ToStrFixed, FormatGrouped |
Types
Rounding
enum Rounding| Name | Type | Description |
|---|---|---|
Down | | Towards zero: the extra digits are thrown away. |
Up | | Away from zero. |
Floor | | Downwards, towards negative infinity. |
Ceil | | Upwards, towards positive infinity. |
HalfUp | | To the nearest, with a half going away from zero. This is the rounding taught at school. |
HalfDown | | To the nearest, with a half going towards zero. |
HalfEven | | To the nearest, with a half going to the even number, known as banker's rounding. Over many additions it keeps the rounding error at zero on average. |
import decimal
func main:
x := decimal.FromScaled(-25, 1)
println decimal.ToStr(decimal.Round(x, 0)), decimal.ToStr(decimal.RoundHalfUp(x, 0)), decimal.ToStr(decimal.Truncate(x, 0))
each mode in [decimal.Rounding.Down, decimal.Rounding.Up, decimal.Rounding.Floor, decimal.Rounding.Ceil, decimal.Rounding.HalfUp, decimal.Rounding.HalfDown, decimal.Rounding.HalfEven]:
print decimal.ToStr(decimal.Rescale(x, 0, mode)), ""
end
println ""
println decimal.ToStr(decimal.Trim(decimal.FromScaled(12500, 4)))
endDec
struct Dec| Name | Type | Description |
|---|---|---|
unscaled | bigint.Int | The whole number without the point; for 10.05 it is 1005. |
scale | int = 0 | The number of digits after the point. |
import decimal
import bigint
func main:
mut a := decimal.FromScaled(1005, 2)
defer a.Free()
println a.ToStr(), a.is_zero(), a.sign()
b := a.Clone()
println decimal.ToStr(b), decimal.Scale(b), bigint.ToStr(decimal.Unscaled(b))
println decimal.ToStr(decimal.Zero()), decimal.ToStr(decimal.FromInt(42))
println decimal.ToStr(decimal.New(bigint.FromInt(31415), 4))
println decimal.ToStr(decimal.FromFloat(0.1, 3))
println decimal.IsZero(decimal.Zero()), decimal.IsNegative(decimal.FromInt(-1)), decimal.Sign(a)
mut c := decimal.Clone(a)
decimal.Free(c)
endFree
func Free()free
func free()The example for this item is shown with the ones above: decimal-Dec.salam
IsZero
func IsZero(): boolis_zero
func is_zero(): boolThe example for this item is shown with the ones above: decimal-Dec.salam
Sign
func Sign(): intsign
func sign(): intThe example for this item is shown with the ones above: decimal-Dec.salam
Clone
func Clone(): Decclone
func clone(): DecThe example for this item is shown with the ones above: decimal-Dec.salam
ToStr
func ToStr(): strto_str
func to_str(): strThe example for this item is shown with the ones above: decimal-Dec.salam
Functions
Zero
func Zero(): DecThe example for this item is shown with the ones above: decimal-Dec.salam
FromInt
func FromInt(v: i64): DecThe example for this item is shown with the ones above: decimal-Dec.salam
FromScaled
func FromScaled(unscaled: i64, scale: int): DecFromScaled(1005, 2) is 10.05. It suits amounts stored in minor units such as cents.The example for this item is shown with the ones above: decimal-Dec.salam
New
func New(unscaled: bigint.Int, scale: int): DecThe example for this item is shown with the ones above: decimal-Dec.salam
Clone
func Clone(d: Dec): DecThe example for this item is shown with the ones above: decimal-Dec.salam
Free
func Free(d &: Dec)The example for this item is shown with the ones above: decimal-Dec.salam
FromFloat
func FromFloat(f: f64, scale: int): Decf64 with the number of decimal places you ask for, rounding half away from zero. The f64's own error is rounded away, so 0.1 to three places is exactly 0.100. The value times 10scale must fit in an i64.The example for this item is shown with the ones above: decimal-Dec.salam
IsZero
func IsZero(d: Dec): boolThe example for this item is shown with the ones above: decimal-Dec.salam
Sign
func Sign(d: Dec): intThe example for this item is shown with the ones above: decimal-Dec.salam
IsNegative
func IsNegative(d: Dec): boolThe example for this item is shown with the ones above: decimal-Dec.salam
Scale
func Scale(d: Dec): intThe example for this item is shown with the ones above: decimal-Dec.salam
Unscaled
func Unscaled(d: Dec): bigint.IntThe example for this item is shown with the ones above: decimal-Dec.salam
Cmp
func Cmp(a: Dec, b: Dec): intimport decimal
func main:
a := decimal.FromScaled(150, 2)
b := decimal.FromScaled(15, 1)
println decimal.Cmp(a, b), decimal.Equals(a, b)
println decimal.Less(a, decimal.FromInt(2)), decimal.Greater(a, decimal.FromInt(2))
println decimal.ToStr(decimal.Min(a, decimal.FromInt(1))), decimal.ToStr(decimal.Max(a, decimal.FromInt(1)))
endEquals
func Equals(a: Dec, b: Dec): boolThe example for this item is shown with the ones above: decimal-Cmp.salam
Less
func Less(a: Dec, b: Dec): boolThe example for this item is shown with the ones above: decimal-Cmp.salam
Greater
func Greater(a: Dec, b: Dec): boolThe example for this item is shown with the ones above: decimal-Cmp.salam
Min
func Min(a: Dec, b: Dec): DecThe example for this item is shown with the ones above: decimal-Cmp.salam
Max
func Max(a: Dec, b: Dec): DecThe example for this item is shown with the ones above: decimal-Cmp.salam
Neg
func Neg(d: Dec): Decimport decimal
func main:
a := decimal.FromScaled(10, 1)
b := decimal.FromScaled(20, 1)
println decimal.ToStr(decimal.Add(a, b)), decimal.ToStr(decimal.Sub(a, b)), decimal.ToStr(decimal.Mul(a, b))
println decimal.ToStr(decimal.Div(a, decimal.FromInt(3), 4, decimal.Rounding.HalfEven))
println decimal.ToStr(decimal.DivRound(a, decimal.FromInt(3), 2))
println decimal.ToStr(decimal.Pow(b, 3)), decimal.ToStr(decimal.Neg(a)), decimal.ToStr(decimal.Abs(decimal.Neg(a)))
println decimal.ToStr(decimal.MulInt(a, 3)), decimal.ToStr(decimal.AddInt(a, 1)), decimal.ToStr(decimal.SubInt(a, 1))
println decimal.ToStr(decimal.DivInt(decimal.FromInt(10), 4, 2, decimal.Rounding.Floor))
println decimal.ToStr(decimal.Percent(decimal.FromInt(250000), decimal.FromInt(9), 0))
endAbs
func Abs(d: Dec): DecThe example for this item is shown with the ones above: decimal-Add.salam
Add
func Add(a: Dec, b: Dec): DecThe example for this item is shown with the ones above: decimal-Add.salam
Sub
func Sub(a: Dec, b: Dec): DecThe example for this item is shown with the ones above: decimal-Add.salam
Mul
func Mul(a: Dec, b: Dec): DecThe example for this item is shown with the ones above: decimal-Add.salam
Div
func Div(a: Dec, b: Dec, scale: int, mode: Rounding): DecThe example for this item is shown with the ones above: decimal-Add.salam
DivRound
func DivRound(a: Dec, b: Dec, scale: int): Decscale places. A zero divisor gives 0.The example for this item is shown with the ones above: decimal-Add.salam
Pow
func Pow(d: Dec, n: int): Decn, exactly; the scale is multiplied by n. A negative n gives 0.The example for this item is shown with the ones above: decimal-Add.salam
MulInt
func MulInt(d: Dec, v: i64): DecThe example for this item is shown with the ones above: decimal-Add.salam
AddInt
func AddInt(d: Dec, v: i64): DecThe example for this item is shown with the ones above: decimal-Add.salam
SubInt
func SubInt(d: Dec, v: i64): DecThe example for this item is shown with the ones above: decimal-Add.salam
DivInt
func DivInt(d: Dec, v: i64, scale: int, mode: Rounding): DecThe example for this item is shown with the ones above: decimal-Add.salam
Percent
func Percent(d: Dec, pct: Dec, scale: int): Decpct per cent of the number, rounded half to even to the given number of places; a 9 per cent tax, for instance.The example for this item is shown with the ones above: decimal-Add.salam
Sum
func Sum(items: Vector<Dec>): Decimport decimal
func main:
total := decimal.FromScaled(10000, 2)
mut shares := decimal.Split(total, 3)
defer decimal.FreeAll(shares)
each s in shares:
print decimal.ToStr(s), ""
end
println ""
println decimal.ToStr(decimal.Sum(shares))
mut ratios := Vector {} as Vector<i64>
defer ratios.Free()
ratios.Push(1 as i64)
ratios.Push(2 as i64)
mut parts := decimal.Allocate(total, ratios)
defer decimal.FreeAll(parts)
each p in parts:
print decimal.ToStr(p), ""
end
println ""
endRescale
func Rescale(d: Dec, scale: int, mode: Rounding): DecThe example for this item is shown with the ones above: decimal-Round.salam
Round
func Round(d: Dec, scale: int): DecThe example for this item is shown with the ones above: decimal-Round.salam
RoundHalfUp
func RoundHalfUp(d: Dec, scale: int): DecThe example for this item is shown with the ones above: decimal-Round.salam
Truncate
func Truncate(d: Dec, scale: int): DecThe example for this item is shown with the ones above: decimal-Round.salam
Trim
func Trim(d: Dec): DecThe example for this item is shown with the ones above: decimal-Round.salam
ToStr
func ToStr(d: Dec): strimport decimal
func main:
mut ok := false
d := decimal.Parse("1234567.891", ok)
println ok, decimal.ToStr(d)
println decimal.ToStrFixed(d, 1), decimal.FormatGrouped(d, 2, ",", ".")
println decimal.ToStr(decimal.ParseOr("not a number"))
mut fits := false
println decimal.ToInt(decimal.FromInt(42), fits), fits, decimal.ToFloat(d)
endToStrFixed
func ToStrFixed(d: Dec, scale: int): strscale decimal places, padding with zeros or rounding half to even.The example for this item is shown with the ones above: decimal-Parse.salam
FormatGrouped
func FormatGrouped(d: Dec, scale: int, group: str, point: str): strscale places, rounded half to even, a group separator every three digits and point as the decimal separator, such as FormatGrouped(d, 2, ",", ".").The example for this item is shown with the ones above: decimal-Parse.salam
Parse
func Parse(s: str, ok &: bool): Dec_ between digits and an exponent such as e3; a comma or ٫ as the decimal point fails. When it cannot parse, ok turns false.The example for this item is shown with the ones above: decimal-Parse.salam
ParseOr
func ParseOr(s: str): DecThe example for this item is shown with the ones above: decimal-Parse.salam
ToInt
func ToInt(d: Dec, ok &: bool): i64ok turns false.The example for this item is shown with the ones above: decimal-Parse.salam
ToFloat
func ToFloat(d: Dec): f64The example for this item is shown with the ones above: decimal-Parse.salam
Split
func Split(total: Dec, n: int): Vector<Dec>n equal shares whose total is exactly the amount; the leftover smallest units go to the first shares, one each. Fewer than one share gives an empty vector.The example for this item is shown with the ones above: decimal-Split.salam
Allocate
func Allocate(total: Dec, ratios: Vector<i64>): Vector<Dec>The example for this item is shown with the ones above: decimal-Split.salam
FreeAll
func FreeAll(v &: Vector<Dec>)The example for this item is shown with the ones above: decimal-Split.salam