Formatting Output with string.format
You can build output with .., but some things are hard that way. For example, a price like 12.5 should show as 12.50. string.format solves this. It builds a string from a template: normal text with placeholders where the values go.
local name = "Alice"
local points = 95
print(string.format("%s scored %d points",
name, points))
Output:
Alice scored 95 points
Each placeholder starts with %. The values come after the template, in the same order as the placeholders. %s was replaced by name, and %d by points.
The three placeholders you need most:
| Placeholder | Use it for |
|---|---|
%s | a string |
%d | a whole number |
%f | a decimal number |
Decimal places
Put .2 between % and f to show exactly two digits after the decimal point:
print(string.format("Total: $%.2f", 12.5))
print(string.format("Total: $%.2f", 3))
print(string.format("%.1f", 2.75))
Output:
Total: $12.50
Total: $3.00
2.8
This is the usual way to print money. %.1f keeps one digit and rounds the rest, so 2.75 became 2.8.
Width
A number before the letter sets a minimum width. The value is padded with spaces to fill it. This helps when you want numbers to line up in columns.
print(string.format("[%5d]", 42))
print(string.format("[%-5d]", 42))
Output:
[ 42]
[42 ]
%5d makes the value 5 characters wide and puts 42 on the right. %-5d puts it on the left.
%d needs a whole number
%d only accepts whole numbers. A number with a fraction is an error, not a rounded result:
print(string.format("%d", 2.5))
Output:
/usr/bin/lua5.4: main.lua:1: bad argument #2 to 'format' (number has no integer representation)
If a number can have a fraction, use %f or %.2f instead.
string.format does not print anything itself. It returns a string, so you can store it in a variable or pass it to print.
In the exercise, finish the template so the total shows with exactly two decimals.