Emmanuel Akinfulubi

JavaScriptString

Right-align numbers in a column in JavaScript

Intermediate · 4 min read

A price list is easy to read when the names line up on the left and the amounts line up on the right, so the last digit of every price sits in the same column. Receipts, command-line tools and plain-text reports all print data this way.

In this tutorial you will print a small price list like that. The trick is to work out the column width from the data itself, so a bigger price never knocks the table out of line. You should know what an array and a function are. The two padding methods are explained below.

Padding in one minute

Padding means adding characters to a string until it reaches a certain length. JavaScript strings have two methods for it:

  • text.padEnd(width, filler) adds filler on the right. The text stays on the left, so this is how you left-align.
  • text.padStart(width, filler) adds filler on the left. The text is pushed to the right, so this is how you right-align.

If you leave out the filler, a space is used. The width is the final length of the whole string, not the number of characters to add.

JavaScript

console.log('Salt'.padEnd(10, '.')); // 'Salt......'
console.log('300'.padStart(6));      // '   300'

Why the font matters

Padding counts characters. That only lines things up when every character is the same width, which is true in a monospaced font, the kind used in terminals and code editors. In normal text an i is narrower than an m, so the columns would still look uneven.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

21 Right-align a column of numbers

fair

Print a small price list so that the names run left and the amounts all end at the same column, whatever their width.

Stuck? Three hints, smallest first
  1. 1. The column width is the length of the longest value, so compute it first.
  2. 2. Left-align with padEnd, right-align with padStart.
  3. 3. A name longer than its column is not truncated by padding, so slice as well when the width is a hard limit.

Step 1: the data, printed the naive way

Each row is a small array: a name and an amount. The first attempt just puts a space between them:

JavaScript

const rows = [['Rice', 4500], ['Palm oil', 12000], ['Salt', 300]];
for (const [name, amount] of rows) console.log(name + ' ' + amount);
// Rice 4500
// Palm oil 12000
// Salt 300

const [name, amount] of rows takes each row apart into two variables. The output is correct but ragged: the amounts start wherever the name happens to end.

Step 2: left-align the names

Give every name the same width with padEnd. Dots make the gap easy to follow with your eye, as on a menu:

JavaScript

console.log('Rice'.padEnd(10, '.'));     // 'Rice......'
console.log('Palm oil'.padEnd(10, '.')); // 'Palm oil..'

Both results are now 10 characters long, so whatever comes next starts in the same place.

Step 3: find the widest amount

To right-align the amounts, you need to know how wide the column must be. Rather than guess, measure the data. Turn each amount into a string and take its length, then pick the biggest:

Step 3

const rows = [['Rice', 4500], ['Palm oil', 12000], ['Salt', 300]];
const width = Math.max(...rows.map(([, amount]) => String(amount).length));
console.log(width); // 5

([, amount]) skips the first item of each row and keeps the second. rows.map(...) gives [4, 5, 3], and the spread ... hands those numbers to Math.max one by one. 12000 is the widest, at 5 digits.

Step 4: right-align the amounts

Now pad each amount on the left to that width. The + 1 adds one more space, so the widest number doesn't touch the dots:

Step 4

const width = 5;
const render = ([name, amount]) =>
  name.padEnd(10, '.') + String(amount).padStart(width + 1);
console.log(render(['Rice', 4500]));      // 'Rice......  4500'
console.log(render(['Palm oil', 12000])); // 'Palm oil.. 12000'
console.log(render(['Salt', 300]));       // 'Salt......   300'

Every line is 16 characters: 10 for the name and 6 for the amount. So every amount ends in the same column.

Step 5: why not just hard-code the width?

You could write padStart(6) and skip Step 3. It works today. But the day a six-figure price arrives, padStart(6) has no room for the gap and the column shifts. Measuring the width from the data means the table adjusts itself.

Step 6: a name that is too long

Padding only ever adds characters. It never removes any:

JavaScript

console.log('A very long product'.padEnd(10, '.'));            // 'A very long product'
console.log('A very long product'.slice(0, 10).padEnd(10, '.')); // 'A very lon'

The long name comes back whole and pushes its amount out of line. If the width is a hard limit, cut the text with slice first, then pad. Padding sets the smallest width and slicing sets the largest; a fixed column needs both.

The full solution

Here is the complete answer: the rows, the measured width, the render function and a loop that prints each line. Press Run to see the table, then read the checks underneath.

The answer

const rows = [['Rice', 4500], ['Palm oil', 12000], ['Salt', 300]];

// The widest amount decides the column, so nothing has to be guessed.
const width = Math.max(...rows.map(([, amount]) => String(amount).length));

const render = ([name, amount]) =>
  name.padEnd(10, '.') + String(amount).padStart(width + 1);

const table = rows.map(render);

for (const line of table) console.log(line);
console.log('column width from the data:', width);

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.

9 checks

test('the widest number sets the column', width, 5);
test('the first row', table[0], 'Rice......  4500');
test('the longest name is padded least', table[1], 'Palm oil.. 12000');
test('every line is the same width', table.map((l) => l.length), [16, 16, 16]);
test('so the amounts all end at the same column', table.every((l) => l.length === table[0].length), true);
test('right alignment is padStart on the number', String(300).padStart(6), '   300');
test('left alignment is padEnd on the name', 'Salt'.padEnd(10, '.'), 'Salt......');
test('a name longer than the column is NOT cut by padding', 'A very long product'.padEnd(10, '.'), 'A very long product');
test('so slice first when the width is a hard limit', 'A very long product'.slice(0, 10).padEnd(10, '.'), 'A very lon');

Deriving the width from the data rather than hard-coding it is the whole point. A hard-coded padStart(6) works until a five-figure number arrives and the column shifts.

The last two assertions are the pair to remember: padding sets a minimum width, slicing sets a maximum, and a fixed-width column needs both. Note also that alignment measured in characters only lines up in a monospaced font — in proportional text you are counting the wrong thing entirely.

Common mistakes

  • Mixing up padStart and padEnd. padStart adds on the left, which pushes text to the right. For right-aligned numbers you want padStart.
  • Calling padStart on a number. Numbers don't have it, so amount.padStart(6) throws a TypeError. Convert with String(amount) first.
  • Expecting padding to cut long text. It never shortens a string. Use slice(0, width) when the column must not grow.

Try it yourself

  1. Add a fourth row, ['Sugar', 150000], and check that the table still lines up without changing any other code.
  2. Measure the name column from the data too, instead of the fixed 10.
  3. Add a last line that shows the total of all amounts, right-aligned in the same column.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.