TExcelTAD
Home › Julia › Julia String Formatting

Julia String Formatting

String interpolation ("$x") is perfect for quick messages, but reports and tables need control over decimals, widths and alignment. Julia's standard library module Printf provides C-style @printf and @sprintf macros for that.

julia · try it yourself
using Printf

price = 1234.5678
@printf("Price: %.2f\n", price)
@printf("%d items at %.1f each\n", 3, 9.95)
s = @sprintf("%08.3f", π)
println(s, " has ", length(s), " characters")
Price: 1234.57
3 items at 9.9 each
0003.142 has 8 characters

@printf prints, @sprintf returns the formatted string. Neither adds a newline, so end the format with \n when you want one. (9.95 shows as 9.9 with one decimal because the binary value of 9.95 is slightly below 9.95.)

Format specifiers

A specifier has the shape %[flags][width][.precision]type.

Type Meaning Example Output
%d / %i integer @sprintf("%d", 42) 42
%f fixed-point decimal @sprintf("%.3f", 2/3) 0.667
%e scientific notation @sprintf("%.2e", 12345.0) 1.23e+04
%g shorter of %f/%e @sprintf("%g", 0.0001) 0.0001
%s any value as text @sprintf("%s", [1,2]) [1, 2]
%c character @sprintf("%c", 'x') x
%x / %o hexadecimal / octal @sprintf("%x", 255) ff
%% a literal percent sign @sprintf("%d%%", 50) 50%
Flag Effect
- left-align within the width
0 pad numbers with zeros
+ always show the sign
julia · try it yourself
using Printf

@printf("[%5d]\n", 42)
@printf("[%-5d]\n", 42)
@printf("[%05d]\n", 42)
@printf("[%+d] [%+d]\n", 7, -7)
@printf("[%10s]\n", "right")
@printf("[%-10s]\n", "left")
@printf("%.2e | %g | %x | %o | %d%%\n", 6.02214e23, 0.5, 255, 8, 75)
[   42]
[42   ]
[00042]
[+7] [-7]
[     right]
[left      ]
6.02e+23 | 0.5 | ff | 10 | 75%

Building a table

Fixed widths line up columns. Here %-10s reserves ten characters for the name (left-aligned) and %8.2f eight for the amount (right-aligned):

julia · try it yourself
using Printf

items = [("Coffee", 3.5, 2), ("Bagel", 2.25, 3), ("Orange juice", 4.0, 1)]
@printf("%-14s %6s %4s %8s\n", "Item", "Price", "Qty", "Total")
println("-"^35)
grand = 0.0
for (name, price, qty) in items
    total = price * qty
    global grand += total
    @printf("%-14s %6.2f %4d %8.2f\n", name, price, qty, total)
end
println("-"^35)
@printf("%-14s %20.2f\n", "Grand total", grand)
Item            Price  Qty    Total
-----------------------------------
Coffee           3.50    2     7.00
Bagel            2.25    3     6.75
Orange juice     4.00    1     4.00
-----------------------------------
Grand total                   17.75

(global is needed because the loop assigns to a global variable in a script; see the Scope lesson.)

Formatting without Printf

For simple needs, Base functions may be enough:

julia · try it yourself
x = 2 / 3
println(round(x, digits=3))
println(round(123456.789, sigdigits=3))
println(lpad(7, 3, "0"))
println(string(255, base=16), " ", string(5, base=2, pad=8))

# A thousands separator by hand
with_commas(n) = reverse(join(Iterators.partition(reverse(string(n)), 3), ","))
println(with_commas(1234567))
0.667
123000.0
007
ff 00000101
1,234,567

Dynamic formats

A format string normally has to be a literal. When you need to build it at run time, create a Printf.Format object and pass it to Printf.format:

julia · try it yourself
using Printf

for width in (4, 8)
    fmt = Printf.Format("|%$(width).1f|\n")
    Printf.format(stdout, fmt, 3.14159)
end
println(Printf.format(Printf.Format("%5.1f%%"), 42.123))
| 3.1|
|     3.1|
 42.1%

Test yourself

What does @sprintf("%06.2f", 3.14159) return?

  1. "3.14"
  2. "003.14"
  3. "3.1416"
  4. "000003"

What is the difference between @printf and @sprintf?

  1. @sprintf adds a newline
  2. @printf prints, @sprintf returns a String
  3. @sprintf is slower
  4. There is none

Which specifier left-aligns a string in a 10-character field?

  1. %10s
  2. %-10s
  3. %+10s
  4. %010s