Standard library · Basics

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:

•

A Sprintf template has no verbs such as %d or {:.2}. A hole is always a bare {}; widths, signs and decimals are set by formatting the value first, with FormatFloat and FormatInt, which take a printf spec such as "%8.2f", or with PadLeft and FloatPrec.

•

A literal {} cannot be written in a template, because there is no escape for it.

•

Hex and Uint take a u64, so an int needs 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.

fmt-guide-receipt.salam
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))
end
Output
|         RECEIPT         |
item          qty    amount
Coffee          2      7.00
Croissant       3      6.75
Water           1      1.00
total                 14.75

Money 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.

fmt-guide-messages.salam
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 })
end
Output
Dear Nima, order #1042 is paid.
Dear Leila, order #1043 is waiting for payment.

The 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.

fmt-guide-colors.salam
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
end
Output
#ffa500
#008080
#090909
  0 #000000
 85 #555555
170 #aaaaaa
255 #ffffff

PadLeft 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.

printf-style numbers

FormatFloat and FormatInt format one number with a C printf spec: flags, a width, a precision and a conversion. The output is the same as C on every backend, rounding included, so fmt.FormatFloat(x, "%.2f") prints what printf("%.2f", x) prints.

PartMeaning
-align to the left inside the width
+ or spaceput + or a space before numbers that are not negative
0pad with zeros after the sign instead of spaces
#keep the decimal point; keep the trailing zeros of g; add 0x, 0b or a leading 0 for octal
widththe smallest number of characters in the result
.precisiondigits after the point for f and e, significant digits for g (6 if left out), the smallest number of digits for whole numbers
f e gfixed, exponent, or the shorter of the two; F E G are the upper case forms
d x X o bdecimal, hex, upper case hex, octal and binary whole numbers
fmt-guide-printf.salam
import fmt

func row(name: str, value: f64):
    println fmt.PadRight(name, 10),
        fmt.FormatFloat(value, "%10.3f"),
        fmt.FormatFloat(value, "%12.4e"),
        fmt.FormatFloat(value, "%g")
end

func main:
    row("pi", 3.14159265358979)
    row("light", 299792458.0)
    row("electron", 0.000000000000000000160218)
    row("change", -0.0425)
    println fmt.FormatFloat(0.125, "%.2f"),
        fmt.FormatFloat(0.135, "%.2f"),
        fmt.FormatFloat(2.5, "%.0f")
    println "#" + fmt.FormatInt(255, "%02x") + fmt.FormatInt(165, "%02x") + fmt.FormatInt(0, "%02x")
    println fmt.FormatInt(42, "%+06d"), fmt.FormatInt(5, "%#b"), fmt.FormatInt(8, "%#o")
end
Output
pi              3.142   3.1416e+00 3.14159
light      299792458.000   2.9979e+08 2.99792e+08
electron        0.000   1.6022e-19 1.60218e-19
change         -0.043  -4.2500e-02 -0.0425
0.12 0.14 2
#ffa500
+00042 0b101 010

Rounding works on the exact value the computer stored, not on the digits you typed. 0.125 is stored exactly, so %.2f rounds the tie to the even digit and gives 0.12; 0.135 is stored as a little more than 0.135, so it gives 0.14. This is also why FormatFloat(2.675, "%.2f") is 2.67 while FloatPrec gives 2.68.

Which function for which job

JobFunction
A whole number as textInt, or Uint for u64
A decimal number, shortest formFloat
A decimal with a fixed number of placesFloatPrec
A number with a printf spec, such as %8.2f, %e or %08xFormatFloat, FormatInt
Align text in a columnPadRight (left aligned), PadLeft (right aligned), Center
A sentence with values in itSprintf, or Fprintf into a file
Base sixteenHex

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): str

Turns a whole number into text, with a minus sign where one is needed.

fmt-Int.salam
import 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) + "]"
end
Output
[-42]
[42]
[3.25]
[3.14]
[true]
[ff]

Float

#
func Float(f: f64): str

Turns a decimal number into the shortest text that reads back as the same number: 1.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

Turns a boolean into "true" or "false".

The example for this item is shown with the ones above: fmt-Int.salam

PadLeft

#
func PadLeft(s: str, width: int): str

If the text is shorter than width, 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.

fmt-PadLeft.salam
import fmt

func main:
    println "[" + fmt.PadLeft("42", 6) + "]"
    println "[" + fmt.PadRight("42", 6) + "]"
    println "[" + fmt.Center("42", 6) + "]"
    println "[" + fmt.PadLeft("salam", 10) + "]"
end
Output
[    42]
[42    ]
[  42  ]
[     salam]

PadRight

#
func PadRight(s: str, width: int): str

Like PadLeft, 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): str

Places the text in the middle of the given width. When the padding does not divide evenly, the extra space goes on the right.

The example for this item is shown with the ones above: fmt-PadLeft.salam

Sprintf

#
func Sprintf(tmpl: str, args: Vector<str>): str

Takes the template and fills each {} in turn from the args vector. If the values run out the remaining holes are left empty, and extra values are ignored.

fmt-Sprintf.salam
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)
end
Output
Sara scored 19.

Fprintf

#
func Fprintf(f: File*, tmpl: str, args: Vector<str>): int

Like Sprintf, but writes the result straight into an open file and returns the number of bytes written.

fmt-Fprintf.salam
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")
end
Output
today it is 25 degrees

FloatPrec

#
func FloatPrec(f: f64, prec: int): str

Turns a decimal number into text with the number of decimal places you ask for. Halves round away from zero, as on paper: 2.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): str

Turns an unsigned 64-bit number into text, for numbers too large to fit in an i64.

The example for this item is shown with the ones above: fmt-Int.salam

Hex

#
func Hex(u: u64): str

Writes the number in base sixteen in lower case, with no 0x 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

FormatFloat

#
func FormatFloat(x: f64, spec: str): str

Formats a decimal number with a printf spec such as "%.2f", "%10.3e" or "%g"; the leading % may be left out. The flags are -, +, space, 0 and #, followed by a width, a precision and one of f F e E g G; with no conversion it uses g. g counts the precision in significant digits, 6 by default, and drops trailing zeros unless # is given. Rounding is exact and matches C: 0.125 with %.2f is 0.12 and 2.5 with %.0f is 2. Not a number and infinity print as nan and inf, or NAN and INF for the upper case conversions, and take the width and sign but not zero padding. A spec it cannot read comes back as %!(spec). Persian and Arabic digits are accepted in the spec too.

fmt-FormatFloat.salam
import fmt

func main:
    println "[" + fmt.FormatFloat(3.14159, "%.2f") + "]"
    println "[" + fmt.FormatFloat(0.125, "%.2f") + "]"
    println "[" + fmt.FormatFloat(-2.5, "%8.1f") + "]"
    println "[" + fmt.FormatFloat(42.0, "%+08.2f") + "]"
    println "[" + fmt.FormatFloat(1234567.0, "%e") + "]"
    println "[" + fmt.FormatFloat(0.0001, "%g") + "]"
    println "[" + fmt.FormatInt(255, "%#x") + "]"
    println "[" + fmt.FormatInt(42, "%-6d") + "]"
    println "[" + fmt.FormatInt(7, "%05d") + "]"
    println "[" + fmt.FormatInt(5, "%b") + "]"
end
Output
[3.14]
[0.12]
[    -2.5]
[+0042.00]
[1.234567e+06]
[0.0001]
[0xff]
[42    ]
[00007]
[101]

FormatInt

#
func FormatInt(n: i64, spec: str): str

Formats a whole number with a printf spec: d or i for decimal, x and X for hex, o for octal and b for binary, with the same flags and width as FormatFloat. The precision is the smallest number of digits, so "%.3d" turns 7 into 007, and when a precision is given the 0 flag is ignored. # adds 0x, 0X or 0b to a number that is not zero, and a leading 0 in octal. A negative number is written as a minus sign and its size in every base, so -255 with %x is -ff. On the JavaScript backend whole numbers beyond 2^53 are not exact.

The example for this item is shown with the ones above: fmt-FormatFloat.salam