fmt
The fmt module turns numbers into text the way reports and receipts need them: a fixed number of decimals, zero padding, thousands separators, and money stored as cents. Tern's f-strings have no format specs ({x:.2f} is an error), so this is where formatting lives. This page covers all six functions and their edge cases.
import fmt
fn main():
print(fmt.fixed(3.14159, 2), fmt.zero_pad(7, 3), fmt.thousands(1234567), fmt.cents(1205))3.14 007 1,234,567 12.05fmt is written in Tern (library/std/fmt.tn); read it if you need to know exactly what happens.
fixed
fn fixed(x: float, digits: int) strx rounded to digits decimal places, always showing exactly that many digits. Halves round away from zero (like math.round), after x is multiplied by 10<sup>digits</sup>.
import fmt
fn main():
print(fmt.fixed(2.0, 3), fmt.fixed(0.125, 2), fmt.fixed(-1.005, 1), fmt.fixed(99.5, 0))
print(fmt.fixed(-0.004, 2), fmt.fixed(1234.5678, 1), fmt.fixed(7.0, -1))2.000 0.13 -1.0 100
0.00 1234.6 7- A value that rounds to zero prints without a minus sign:
fixed(-0.004, 2)is"0.00". digitsof 0 or less gives a whole number with no decimal point.- There is no digit grouping; combine with
thousandsfor that (see the example at the end). - Binary floats can't store most decimals exactly, so a value that looks like a tie may round either way:
2.675is really2.67499999.... For money, store integer cents and usecents. - The rounded value times 10<sup>digits</sup> must fit in an
int(about 9.2 × 10<sup>18</sup>). Larger values, infinities, and NaN give meaningless text. Check withx == x(false for NaN) before formatting untrusted numbers.
cents
fn cents(n: int) strAn amount stored as an integer number of cents, as a decimal with two places. Integer cents are the safe way to handle money: adding them never loses a cent.
import fmt
fn main():
prices = [1999, 250, 5]
total = 0
for p in prices:
total += p
print(fmt.cents(total), fmt.cents(-5), fmt.cents(0), fmt.cents(100000))22.54 -0.05 0.00 1000.00zero_pad
fn zero_pad(n: int, width: int) strn with leading zeros to make it width characters long. For a negative number the minus sign counts toward the width and the zeros go after it. A number that is already width characters or longer is returned unchanged.
import fmt
fn main():
print(fmt.zero_pad(5, 2), fmt.zero_pad(-5, 3), fmt.zero_pad(12345, 3), fmt.zero_pad(0, 4))
hours = 9
minutes = 5
print(f"{fmt.zero_pad(hours, 2)}:{fmt.zero_pad(minutes, 2)}")05 -05 12345 0000
09:05pad_left
fn pad_left(s: str, width: int, fill: str) strs with copies of fill added on the left until it is width bytes long. Use it to right-align columns. Text already width bytes or longer is returned unchanged (never cut).
pad_right
fn pad_right(s: str, width: int, fill: str) strs with copies of fill added on the right until it is width bytes long. Use it to left-align columns.
import fmt
fn main():
names = ["apple", "fig", "watermelon"]
counts = [12, 7, 130]
for i, name in names:
print("[" + fmt.pad_right(name, 12, ".") + fmt.pad_left(str(counts[i]), 5, " ") + "]")[apple....... 12]
[fig......... 7]
[watermelon.. 130]Both functions count bytes, like len. For ASCII text that is the same as characters, but a letter such as é is two bytes, so text containing it comes out one column short. fill should be one character: a longer fill is repeated whole, so the result can be longer than width.
thousands
fn thousands(n: int) strn with a comma between each group of three digits.
import fmt
fn main():
print(fmt.thousands(1234567), fmt.thousands(-9876543210), fmt.thousands(999), fmt.thousands(0))1,234,567 -9,876,543,210 999 0The separator is always a comma; for other conventions, replace it: fmt.thousands(n).replace(",", ".").
A complete example
An invoice printed as an aligned table. Prices are kept in integer cents, so the total is exact:
import fmt
struct Line:
item: str
qty: int
unit_cents: int
fn money(c: int) str: # c >= 0: 129900 -> "1,299.00"
return fmt.thousands(c / 100) + "." + fmt.zero_pad(c % 100, 2)
fn main():
lines = [Line("Keyboard", 2, 4999), Line("Monitor", 1, 129900), Line("Cable", 5, 399)]
total = 0
print(fmt.pad_right("item", 10, " ") + fmt.pad_left("qty", 5, " ") + fmt.pad_left("amount", 12, " "))
for l in lines:
amount = l.qty * l.unit_cents
total += amount
print(fmt.pad_right(l.item, 10, " ") + fmt.pad_left(str(l.qty), 5, " ") + fmt.pad_left(money(amount), 12, " "))
print(fmt.pad_right("total", 15, " ") + fmt.pad_left(money(total), 12, " "))
tax_rate = 0.0825
print("tax at " + fmt.fixed(tax_rate * 100.0, 2) + "%: " + fmt.cents(int(float(total) * tax_rate + 0.5)))item qty amount
Keyboard 2 99.98
Monitor 1 1,299.00
Cable 5 19.95
total 1,418.93
tax at 8.25%: 117.06