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 Mul adds 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, Round and Percent round half to even, so 2.345 shows as 2.34. Call RoundHalfUp first when you want 2.35.
•
Dividing by zero. Div, DivRound and DivInt return 0 instead of stopping the program, so check the divisor yourself.
•
Copying with =. A Dec holds a bigint.Int, so b := a shares its digits; use Clone for 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.
decimal-guide-float.salam
import decimal
funcmain:
mut f := 0.0repeat10:
f += 0.1endprintln"f64 sum of ten 0.1:", f, f == 1.0mut d := decimal.Zero()
tenth := decimal.FromScaled(1, 1)
repeat10:
d = decimal.Add(d, tenth)
endprintln"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))
end
Output
f64 sum of ten 0.1: 0.9999999999999999 false
decimal sum of ten 0.1: 1.0 true
19.99 from f64: 19.99
times 3: 59.97
An 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.
Notebook 3 x 4.75 = 14.25
Pen 10 x 1.20 = 12.00
Backpack 1 x 39.90 = 39.90
subtotal 66.15
discount 5% 3.31
tax 9.5% 5.97
total 68.81
Round 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.
year 1 interest 150.00 balance 10,150.00
year 2 interest 152.25 balance 10,302.25
year 3 interest 154.53 balance 10,456.78
year 4 interest 156.85 balance 10,613.63
year 5 interest 159.20 balance 10,772.83
without yearly rounding 10772.840038843750000
rounded 10772.84
a twelfth, rounded down 897.73
Splitting 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.
decimal-guide-split.salam
import decimal
funcshow(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)
endfuncmain:
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 {} asVector<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)
end
Output
100.00 / 3 rounded: 33.33 x 3 = 99.99
split in 3: 33.34 33.33 33.33 | total 100.00
50/30/20 of 1234.57: 617.29 370.37 246.91 | total 1234.57
The 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.
decimal-guide-parse.salam
import decimal
funcmain:
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"endendprintln decimal.ToStr(decimal.ParseOr("oops"))
end
Output
[1250.50] -> 1250.50 scale 2
[ -3.75 ] -> -3.75 scale 2
[1_000_000] -> 1000000 scale 0
[۱۲۳.۴۵] -> 123.45 scale 2
[۱۲۳٫۴۵] -> not a number
[2.5e3] -> 2500 scale 0
[12,50] -> not a number
[abc] -> not a number
[] -> not a number
0
Scientific 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.
decimal-guide-pitfalls.salam
import decimal
funcmain:
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)
repeat3:
grown = decimal.Mul(grown, rate)
endprintln"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"endend
Output
ToStrFixed rounds half to even: 2.34
RoundHalfUp first: 2.35
Mul adds the scales: 2.520875 scale 6
three more times: 3.131675134765625 scale 15
rounded to cents: 3.13
shared among zero staff: 0.00
check the divisor before you divide
FromFloat has a limit of its own: it multiplies the f64 by ten for each place and converts to i64, so a value times 10^scale must stay below about 9.2 × 10^18. For large amounts, parse text instead.
Converts an f64 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 10^scale must fit in an i64.
The example for this item is shown with the ones above: decimal-Dec.salam
funcDiv(a: Dec, b: Dec, scale: int, mode: Rounding): Dec
Division with the number of decimal places and the rounding method you give; a negative scale counts as 0. A zero divisor gives 0 rather than an error.
The example for this item is shown with the ones above: decimal-Add.salam
Divides an amount into 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.
Divides an amount by the given whole-number ratios, keeping the total exactly the amount; the leftover units go to the first shares. A negative ratio or a zero total ratio gives an empty vector.
The number as text with scale places, rounded half to even, a group separator every three digits and point as the decimal separator, such as FormatGrouped(d, 2, ",", ".").
Turns text into a decimal. It skips spaces at both ends and accepts a sign, Persian or Arabic digits, _ between digits and an exponent such as e3; a comma or ٫ as the decimal point fails. When it cannot parse, ok turns false.