print and println@printftry-catch for Exception Handlingfinally@printfWhile print and println are excellent for quick and straightforward output to the console, there are many situations where you need finer control over how your data is displayed. You might want to align numbers in columns, specify the number of decimal places for a floating-point value, or pad strings with spaces. For these tasks, Julia provides the @printf macro, a powerful tool for producing precisely formatted text. This macro is part of the Printf module in Julia's standard library, which is readily available without needing an explicit import.
The @printf macro works similarly to the printf function found in C and other programming languages. It takes a format string as its first argument, followed by one or more values that you want to format and print.
@printfThe general syntax for using @printf is:
@printf "format_string" value1 value2 ...
The format_string contains regular text that is printed as is, along with special sequences called format specifiers. Each format specifier acts as a placeholder that defines how a corresponding value should be formatted. These specifiers always begin with a percent sign (%).
Let's look at a simple example:
name = "Julia"
version = 1.9
@printf "To %s version %.1f!\n" name version
# Output: Welcome to Julia version 1.9!
In this example:
%s is a format specifier for a string. It's replaced by the value of the name variable.%.1f is a format specifier for a floating-point number. It's replaced by the value of the version variable, formatted to one decimal place.\n is an escape sequence that represents a newline character, moving the cursor to the next line after printing. Unlike println, @printf does not automatically add a newline.Here are some of the most frequently used format specifiers with @printf:
%s: Formats a value as a string.
language = "Julia"
@printf "Current language: %s\n" language
# Output: Current language: Julia
%d: Formats an integer as a decimal number.
count = 10
@printf "There are %d items.\n" count
# Output: There are 10 items.
%f: Formats a floating-point number in standard decimal notation (e.g., 123.45).
price = 19.99
@printf "The price is %f.\n" price
# Output: The price is 19.990000. (Default precision is usually 6 decimal places)
%e or %E: Formats a floating-point number in scientific notation (e.g., 1.2345e+02 or 1.2345E+02).
large_number = 123450000.0
@printf "Scientific: %e\n" large_number
# Output: Scientific: 1.234500e+08
%g or %G: Formats a floating-point number using either %f or %e (or %E) notation, whichever is more compact for the given value and precision. This is often a good general-purpose choice for floats.
val1 = 0.0000123
val2 = 12345.6
@printf "Compact val1: %g, Compact val2: %g\n" val1 val2
# Output: Compact val1: 1.23e-5, Compact val2: 12345.6
%c: Formats a single character.
initial = 'J'
@printf "Initial: %c\n" initial
# Output: Initial: J
%%: Prints a literal percent sign.
percentage = 75
@printf "Discount: %d%%\n" percentage
# Output: Discount: 75%
One of the main strengths of @printf is its ability to control the layout of your output.
You can specify a minimum width for a field by putting a number directly after the %. If the value is shorter than the specified width, it will be padded with spaces (by default, on the left, making it right-aligned).
id = 42
name = "Widget"
@printf "ID: %5d, Name: %10s\n" id name
# Output: ID: 42, Name: Widget
Here, %5d means "print the integer in a field of at least 5 characters wide." %10s means "print the string in a field of at least 10 characters wide."
By default, numbers are right-aligned and strings are often right-aligned too (though this can sometimes depend on the system or specific Julia version subtleties; explicit alignment is best for strings if it matters). You can force left-alignment by placing a hyphen (-) before the width specifier.
id = 42
name = "Widget"
@printf "ID: %-5d, Name: %-10s END\n" id name
# Output: ID: 42 , Name: Widget END
Notice how 42 is now padded with spaces on the right to fill 5 characters, and "Widget" is padded on the right to fill 10 characters.
For floating-point numbers (%f, %e, %g), you can specify the number of digits to display after the decimal point. This is done by adding a period (.) followed by the number of decimal places, before the type specifier.
pi_approx = 3.1415926535
@printf "Pi (default %%f): %f\n" pi_approx
@printf "Pi (%.2f): %.2f\n" pi_approx
@printf "Pi (%.4f): %.4f\n" pi_approx
# Output:
# Pi (default %f): 3.141593
# Pi (%.2f): 3.14
# Pi (%.4f): 3.1416 (Note: rounding occurs)
You can combine width and precision:
value = 12.345
@printf "Value: |%10.2f|\n" value
# Output: Value: | 12.35|
This formats value to two decimal places, within a total field width of 10 characters, right-aligned.
If you want to pad numbers with leading zeros instead of spaces, place a 0 immediately after the % or after the alignment specifier (if any).
item_number = 7
@printf "Item: %03d\n" item_number
# Output: Item: 007
amount = 5.2
@printf "Amount: %08.2f\n" amount # Pad with zeros to width 8, 2 decimal places
# Output: Amount: 00005.20
You can, and often will, use multiple format specifiers in a single format_string. The values you provide after the string will be matched to the specifiers in the order they appear.
product = "Laptop"
quantity = 3
unit_price = 1200.50
@printf "Item: %-15s Quantity: %3d Unit Price: $%8.2f\n" product quantity unit_price
# Output: Item: Laptop Quantity: 3 Unit Price: $ 1200.50
\n)A common point of confusion for new users is that @printf does not automatically add a newline character at the end of the output, unlike println. If you want subsequent output to appear on a new line, you must include \n in your format string.
@printf "First line."
@printf "Still on the first line."
@printf "\nNow on the second line.\n"
# Output:
# First line.Still on the first line.
# Now on the second line.
Printf.sprintfSometimes, you don't want to print the formatted text directly to the console. Instead, you might want to store it in a variable, write it to a file, or use it in another part of your program. For this, the Printf module provides the sprintf function (note: it's a function, not a macro, so no @ prefix).
sprintf takes the same format string and arguments as @printf, but instead of printing, it returns the resulting formatted string.
using Printf # Required for sprintf if not already in scope via @printf
item_name = "Sensor"
value = 23.5789
formatted_data = Printf.sprintf("%s reading: %.2f units", item_name, value)
println(formatted_data)
# Output: Sensor reading: 23.58 units
# You can now use formatted_data, e.g., write it to a file
Let's put some of these formatting options together to create a neatly aligned table of data. This is a common use case where @printf shines.
# Data for our table
students = [
("Alice", 85, 92.5),
("Bob", 78, 88.0),
("Charlie", 91, 95.75)
]
# Print table header
@printf "%-10s | %8s | %10s\n" "Name" "Midterm" "Final Grade"
@printf "-----------|----------|------------\n" # Separator line
# Print table rows
for (name, midterm_score, final_grade) in students
@printf "%-10s | %8d | %10.2f\n" name midterm_score final_grade
end
This will produce the following output:
Name | Midterm | Final Grade
-----------|----------|------------
Alice | 85 | 92.50
Bob | 78 | 88.00
Charlie | 91 | 95.75
Notice how:
%-10s left-aligns the names in a field of 10 characters.%8d right-aligns the integer midterm scores in a field of 8 characters.%10.2f right-aligns the final grades, formatted to two decimal places, in a field of 10 characters.The @printf macro offers a great deal of control for presenting textual data in a structured and readable way. Experimenting with different specifiers and options is the best way to become comfortable with its capabilities.
Was this section helpful?
© 2026 ApX Machine LearningEngineered with