Print a receipt with aligned columns in JavaScript
Advanced · 4 min read
Till receipts, terminal reports and plain-text emails all have the same look: names on the left, numbers on the right, every column lined up. There is no table behind them. Each line is just text, padded with spaces to exactly the right length.
In this tutorial you will print a three-item receipt with an item column, a quantity column and an amount column, then a line and a total. You'll see what happens when an item name is too long, and why the money is added up in kobo rather than naira. You need to know strings, arrays and map. Padding and the money format are explained below.
padStart and padEnd
padEnd(width) adds spaces to the end of a string until it is width characters long. padStart(width) adds them to the start. Text columns are usually left-aligned with padEnd, and number columns right-aligned with padStart, so the digits line up.
console.log('[' + 'Suya'.padEnd(8) + ']'); // [Suya ]
console.log('[' + '45'.padStart(5) + ']'); // [ 45]
console.log('[' + 'Jollof rice'.padEnd(5) + ']'); // [Jollof rice]
Look at the last line. Padding only ever adds. A string that is already longer than the width comes back unchanged, so it pushes the next column along.
Why kobo?
A naira is 100 kobo. If you add prices as decimals like 1500.55, you can get tiny errors, because computers store most decimals approximately:
console.log(2 * 1500.55 + 3 * 500.15 + 1200.05); // 5701.599999999999
console.log(2 * 150055 + 3 * 50015 + 120005); // 570160
Whole numbers of kobo add up exactly. We only turn them into naira text at the moment we print.
Here is the exercise. Try it on your own first if you like, or read on and we will build it together.
125 A receipt with columns that line up
hardPrint a three-item receipt as fixed-width text: item name in a 16-character column, quantity right-aligned in 3, amount right-aligned in 11, then a rule and a total row. Keep every line the same width even when an item name is too long for its column.
Stuck? Three hints, smallest first
- 1.
padEndfor the left column,padStartfor the numbers. - 2. Padding never truncates, so a long name must be cut before it is padded.
- 3. Total in kobo as integers, and format only at the moment of printing.
Step 1: format kobo as naira
const SIGN = '\u20a6';
const group = (n) => String(n).replace(/\B(?=(\d{3})+$)/g, ',');
const naira = (kobo) => SIGN + group(Math.trunc(kobo / 100)) + '.' + String(kobo % 100).padStart(2, '0');
console.log(naira(570160)); // ₦5,701.60
console.log(naira(50)); // ₦0.50
console.log(naira(5)); // ₦0.05
'\u20a6' is the naira sign, ₦, written as a code so the file stays plain text. Math.trunc(kobo / 100) gives the whole naira, and kobo % 100 the kobo left over. padStart(2, '0') keeps two places, so 5 kobo prints 0.05, not 0.5.
group puts in the thousands commas. It uses a regular expression that finds every spot followed by a multiple of three digits. The exercise on formatting a number with commas explains it in detail. Here you can treat it as a tool.
Step 2: one row
const SIGN = '\u20a6';
const NAME_WIDTH = 16;
const AMOUNT_WIDTH = 11;
const group = (n) => String(n).replace(/\B(?=(\d{3})+$)/g, ',');
const naira = (kobo) => SIGN + group(Math.trunc(kobo / 100)) + '.' + String(kobo % 100).padStart(2, '0');
function row(name, qty, kobo) {
return name.padEnd(NAME_WIDTH) + String(qty).padStart(3) + naira(kobo).padStart(AMOUNT_WIDTH);
}
console.log(row('Jollof rice', 2, 300110));
console.log(row('Jollof rice', 2, 300110).length); // 30
console.log(row('Chapman with extra ice', 1, 120005).length); // 36
Each row is the name padded to 16, the quantity right-aligned in 3, and the amount right-aligned in 11: 30 characters in total. The first row prints as Jollof rice 2 ₦3,001.10.
The long drink name, though, makes a 36-character line. Its quantity and amount sit six places to the right of everyone else's.
Step 3: cut long names before padding
const NAME_WIDTH = 16;
function label(name) {
return name.length > NAME_WIDTH ? name.slice(0, NAME_WIDTH - 1) + '\u2026' : name;
}
console.log(label('Chapman with extra ice')); // Chapman with ex…
console.log(label('Suya')); // Suya
console.log(label('Chapman with extra ice').length); // 16
'\u2026' is the ellipsis character, …, which is one character wide. We keep 15 letters and add it, making exactly 16. Short names are left alone, and padEnd fills them out later.
So the rule is cut, then pad. Padding alone can never make a column narrower.
Step 4: the whole receipt
const SIGN = '\u20a6';
const NAME_WIDTH = 16;
const AMOUNT_WIDTH = 11;
const group = (n) => String(n).replace(/\B(?=(\d{3})+$)/g, ',');
const naira = (kobo) => SIGN + group(Math.trunc(kobo / 100)) + '.' + String(kobo % 100).padStart(2, '0');
function row(name, qty, kobo) {
const label = name.length > NAME_WIDTH ? name.slice(0, NAME_WIDTH - 1) + '\u2026' : name;
return label.padEnd(NAME_WIDTH) + String(qty).padStart(3) + naira(kobo).padStart(AMOUNT_WIDTH);
}
const ITEMS = [
{ name: 'Jollof rice', qty: 2, unit: 150055 },
{ name: 'Suya', qty: 3, unit: 50015 },
{ name: 'Chapman with extra ice', qty: 1, unit: 120005 },
];
const lines = ITEMS.map((it) => row(it.name, it.qty, it.qty * it.unit));
const total = ITEMS.reduce((sum, it) => sum + it.qty * it.unit, 0);
const totalRow = row('TOTAL', ITEMS.reduce((n, it) => n + it.qty, 0), total);
const receipt = [...lines, '-'.repeat(NAME_WIDTH + 3 + AMOUNT_WIDTH), totalRow].join('\n');
console.log(receipt);
console.log([...new Set(receipt.split('\n').map((l) => l.length))]); // [ 30 ]
The receipt prints as:
Jollof rice 2 ₦3,001.10
Suya 3 ₦1,500.45
Chapman with ex… 1 ₦1,200.05
------------------------------
TOTAL 6 ₦5,701.60
map builds one row per item, and reduce adds up the kobo and the quantities. The dashed rule is the three widths added together, so it always matches. The last line collects every line's length into a Set, which keeps only distinct values. One value, 30, means every line is the same width.
These columns only line up in a monospaced font, where every character is the same width. In a normal web page font, use a table or a grid instead.
The full solution
The answer panel has the complete receipt code and prints it. The checks confirm every line is 30 wide, the amount is right-aligned, the long name is cut, the total is exactly 570160 kobo, and the decimal version is not. Press Run to see the output.
const SIGN = '\u20a6';
const NAME_WIDTH = 16;
const AMOUNT_WIDTH = 11;
const group = (n) => String(n).replace(/\B(?=(\d{3})+$)/g, ',');
const naira = (kobo) => SIGN + group(Math.trunc(kobo / 100)) + '.' + String(kobo % 100).padStart(2, '0');
function row(name, qty, kobo) {
const label = name.length > NAME_WIDTH ? name.slice(0, NAME_WIDTH - 1) + '\u2026' : name;
return label.padEnd(NAME_WIDTH) + String(qty).padStart(3) + naira(kobo).padStart(AMOUNT_WIDTH);
}
const ITEMS = [
{ name: 'Jollof rice', qty: 2, unit: 150055 }, // kobo
{ name: 'Suya', qty: 3, unit: 50015 },
{ name: 'Chapman with extra ice', qty: 1, unit: 120005 },
];
const lines = ITEMS.map((it) => row(it.name, it.qty, it.qty * it.unit));
const total = ITEMS.reduce((sum, it) => sum + it.qty * it.unit, 0);
const totalRow = row('TOTAL', ITEMS.reduce((n, it) => n + it.qty, 0), total);
const receipt = [...lines, '-'.repeat(NAME_WIDTH + 3 + AMOUNT_WIDTH), totalRow].join('\n');
console.log(receipt);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('every line is exactly the same width', [...new Set(receipt.split('\n').map((l) => l.length))], [30]);
test('the amount column is right-aligned inside its width', lines[0].slice(NAME_WIDTH + 3), ' ' + SIGN + '3,001.10');
test('a name too long for the column is cut, with an ellipsis', lines[2].slice(0, NAME_WIDTH), 'Chapman with ex\u2026');
test('padding it instead would have overflowed by six', 'Chapman with extra ice'.padEnd(NAME_WIDTH).length, 22);
test('the total is an exact integer number of kobo', total, 570160);
test('printed with a thousands separator and two places', naira(total), SIGN + '5,701.60');
test('the same total added up as naira floats is not that number', 2 * 1500.55 + 3 * 500.15 + 1200.05, 5701.599999999999);
test('an amount under one naira keeps both places', naira(50), SIGN + '0.50');
test('and the quantity column carries the item count', totalRow.slice(NAME_WIDTH, NAME_WIDTH + 3), ' 6');
Alignment is subtraction, and the trap is that padEnd only ever adds. A name of 22 characters comes back 22 characters long, the quantity column starts six places late, and every row below it in that column is crooked — so the name must be cut to fit and then padded (exercises 37 and 103 are the two halves of that). Cutting to NAME_WIDTH - 1 leaves room for the ellipsis, which is itself one character.
The float assertion is the reason the units are kobo. The same three amounts added as naira decimals come to 5701.599999999999, so a receipt built that way prints ₦5,701.5999999999995 or, once rounded for display, a total that does not equal the sum of the lines shown above it — the complaint arrives from the customer, not the test suite (exercise 61 is the underlying arithmetic; exercise 74 the formatting). Integers throughout, formatted once at the edge.
Two limits worth stating. String(kobo % 100) assumes a non-negative amount, so a refund line needs the sign handling from exercise 74. And fixed-width columns only line up in a monospaced font: the same receipt in a proportional font is ragged no matter how carefully the spaces are counted, which is why the browser version of this is a table or a grid, not padding.
Common mistakes
- Padding without cutting.
padEndnever shortens, so one long name knocks every column out of line. - Adding money as decimals. The total can come out as
5701.599999999999. Use whole kobo and format at the end. - Forgetting
padStart(2, '0')on the kobo. 5 kobo would print as₦0.5, which reads like 50 kobo.
Try it yourself
- Add a fourth item,
'Puff-puff', 6 at 2000 kobo each, and check every line is still 30 wide. - Add a VAT line at 7.5% of the total, rounded to whole kobo, and a grand total under it.
- Make
NAME_WIDTH12 and see which names get cut.