fmt
Turning numbers and booleans into text, aligning text, and building a string from a template.
import fmt
When you want tidy, readable output, the fmt package is what you reach for. With it you turn numbers into text, line text up in fixed-width columns, and build sentences from a template.
The templates are simple: every {} in the template is filled with the next element of the vector of values. Since the values are strings, convert numbers first with a function such as Int.
Coming from printf or Go, watch for these:
- There are no verbs such as
%dor{:.2}. A hole is always a bare{}; widths and decimals are set by formatting the value first withPadLeftorFloatPrec. - A literal
{}cannot be written in a template, because there is no escape for it. HexandUinttake au64, so anintneeds a cast:fmt.Hex(n as u64).
Printing a table
A table in plain text is a row of padded cells. Text columns read best aligned to the left with PadRight, and number columns aligned to the right with PadLeft, so the digits of each place line up. A small helper that builds one row keeps every line of the table the same shape, header included.
import fmt
struct Line:
pub name: str = ""
pub qty: int = 0
pub price: f64 = 0.0
end
func row(a: str, b: str, c: str): str:
ret fmt.PadRight(a, 12) + fmt.PadLeft(b, 5) + fmt.PadLeft(c, 10)
end
func main:
items := [Line { name = "Coffee", qty = 2, price = 3.5 }, Line { name = "Croissant", qty = 3, price = 2.25 }, Line { name = "Water", qty = 1, price = 1.0 }]
println "|" + fmt.Center("RECEIPT", 25) + "|"
println row("item", "qty", "amount")
mut total := 0.0
each it in items:
amount := it.price * it.qty
total += amount
println row(it.name, fmt.Int(it.qty), fmt.FloatPrec(amount, 2))
end
println row("total", "", fmt.FloatPrec(total, 2))
endMoney is printed with FloatPrec and two places, so 7 shows as 7.00 and every amount has the same width. The widths count characters, not bytes, so the same code lines up Persian or Arabic names too. A value longer than its column is never cut, it only pushes the rest of the row to the right; pick widths that fit your longest value.
If the names are in Persian or Arabic and you look at the table in a terminal, the columns may appear in a different order, because how mixed right-to-left text and numbers are shown depends on the Unicode bidirectional algorithm. The strings themselves are correct; for exact display on the web, use an HTML table.
Filling a message template
Sprintf fills each {} with the next string from a vector. Keeping the sentence in one template, instead of a long chain of +, makes it easy to read and easy to change later, or to swap for a translated template. Numbers and booleans go in through Int, Float or Bool first, because every value is a string.
import fmt
struct Order:
pub customer: str = ""
pub id: int = 0
pub paid: bool = false
end
func notice(o: Order): str:
mut args := Vector {} as Vector<str>
defer args.Free()
args.Push(o.customer)
args.Push(fmt.Int(o.id))
args.Push(o.paid ? "paid" : "waiting for payment")
ret fmt.Sprintf("Dear {}, order #{} is {}.", args)
end
func main:
println notice(Order { customer = "Nima", id = 1042, paid = true })
println notice(Order { customer = "Leila", id = 1043 })
endThe vector of values belongs to you, so free it when the message is built. When the result should go to a file instead of a string, Fprintf takes the same template and values and writes them to an open File*.
Hexadecimal output
Hex writes a number in base sixteen with lower case letters and no 0x, and it does not add leading zeros. Formats with a fixed width, such as a CSS color where each channel is exactly two digits, need that zero added by hand.
import fmt
func two_hex(n: int): str:
h := fmt.Hex(n as u64)
if h.Len() < 2:
ret "0" + h
end
ret h
end
func css_color(r: int, g: int, b: int): str:
ret "#" + two_hex(r) + two_hex(g) + two_hex(b)
end
func main:
println css_color(255, 165, 0)
println css_color(0, 128, 128)
println css_color(9, 9, 9)
mut shade := 0
until shade <= 255:
println fmt.PadLeft(fmt.Int(shade), 3), css_color(shade, shade, shade)
shade += 85
end
endPadLeft always pads with spaces, which is right for the shade column on the left but not for hex digits. For anything bigger than one byte, compare the length with the width you need and add as many zeros as are missing.
Which function for which job
| Job | Function |
|---|---|
| A whole number as text | Int, or Uint for u64 |
| A decimal number, shortest form | Float |
| A decimal with a fixed number of places | FloatPrec |
| Align text in a column | PadRight (left aligned), PadLeft (right aligned), Center |
| A sentence with values in it | Sprintf, or Fprintf into a file |
| Base sixteen | Hex |
For parsing text back into numbers, see conv. For templates with names, loops and conditions, such as an HTML page or an email, use template.
Functions
Int
func Int(i: i64): strimport fmt
func main:
println "[" + fmt.Int(-42) + "]"
println "[" + fmt.Uint(42 as u64) + "]"
println "[" + fmt.Float(3.25) + "]"
println "[" + fmt.FloatPrec(3.14159, 2) + "]"
println "[" + fmt.Bool(true) + "]"
println "[" + fmt.Hex(255 as u64) + "]"
endFloat
func Float(f: f64): str1.0 becomes 1, 0.1 stays 0.1 and 1.0 / 3.0 becomes 0.3333333333333333. Very large or very small numbers use an exponent, such as 1e+21. Use FloatPrec when the number of places must be fixed.The example for this item is shown with the ones above: fmt-Int.salam
Bool
func Bool(b: bool): str"true" or "false".The example for this item is shown with the ones above: fmt-Int.salam
PadLeft
func PadLeft(s: str, width: int): strwidth, adds spaces on its left until it reaches that width. The width counts characters, so it behaves correctly outside ASCII too. In a column of numbers this is what lines them up on the right.import fmt
func main:
println "[" + fmt.PadLeft("42", 6) + "]"
println "[" + fmt.PadRight("42", 6) + "]"
println "[" + fmt.Center("42", 6) + "]"
println "[" + fmt.PadLeft("salam", 10) + "]"
endPadRight
func PadRight(s: str, width: int): strPadLeft, but puts the spaces on the right of the text.The example for this item is shown with the ones above: fmt-PadLeft.salam
Center
func Center(s: str, width: int): strThe example for this item is shown with the ones above: fmt-PadLeft.salam
Sprintf
func Sprintf(tmpl: str, args: Vector<str>): str{} in turn from the args vector. If the values run out the remaining holes are left empty, and extra values are ignored.import fmt
func main:
mut values := Vector {} as Vector<str>
defer values.Free()
values.Push("Sara")
values.Push(fmt.Int(19))
println fmt.Sprintf("{} scored {}.", values)
endFprintf
func Fprintf(f: File*, tmpl: str, args: Vector<str>): intSprintf, but writes the result straight into an open file and returns the number of bytes written.import fmt
import io
import os
func main:
mut values := Vector {} as Vector<str>
defer values.Free()
values.Push("25")
f := os.Open("temperature.txt", "wb")
fmt.Fprintf(f, "today it is {} degrees\n", values)
io.Close(f)
print io.ReadFile("temperature.txt")
endFloatPrec
func FloatPrec(f: f64, prec: int): str2.675 with two places is 2.68 and -1.5 with none is -2.The example for this item is shown with the ones above: fmt-Int.salam
Uint
func Uint(u: u64): stri64.The example for this item is shown with the ones above: fmt-Int.salam
Hex
func Hex(u: u64): str0x prefix and no leading zeros. It takes a u64, so cast an int with as u64.The example for this item is shown with the ones above: fmt-Int.salam