Emmanuel Akinfulubi

JavaScriptBasic

Convert a number to Roman numerals in JavaScript

Intermediate · 3 min read

Roman numerals still turn up in clock faces, book chapters, film credits, sporting events like the Super Bowl, and the names of kings and queens. Writing a converter is also a classic programming exercise, because it teaches a useful technique called a greedy loop.

In this tutorial you will write toRoman(n), which turns 1994 into MCMXCIV, and refuses any number it can't write. You need to know what an array is, how for...of and while loops work, and how to throw an error.

How Roman numerals work

There are seven symbols:

Output

I = 1    V = 5    X = 10    L = 50    C = 100    D = 500    M = 1000

You write a number by putting symbols in a row, biggest first, and adding them up: MMXXVI is 1000 + 1000 + 10 + 10 + 5 + 1 = 2026.

There is one twist. Four is not written IIII. It is IV, "one before five". A smaller symbol placed in front of a bigger one is subtracted. Only six of these pairs are used:

Output

IV = 4    IX = 9    XL = 40    XC = 90    CD = 400    CM = 900

There is no symbol for zero, and the largest number you can write with these seven letters is 3999 (MMMCMXCIX).

The greedy idea

To write a number, keep taking the biggest symbol that still fits. For 1994: M (1000) fits, leaving 994. CM (900) fits, leaving 94. XC (90) fits, leaving 4. IV (4) fits, leaving 0. Put those together: MCMXCIV.

It is called greedy because it always grabs the biggest piece it can.

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

72 A number as Roman numerals

fair

Write 1994 as MCMXCIV. Refuse anything outside 1 to 3999.

Stuck? Three hints, smallest first
  1. 1. List the values largest first, including the subtractive pairs CM, CD, XC, XL, IX and IV.
  2. 2. Then it is a greedy loop: while the number is at least this value, append the symbol and subtract.
  3. 3. There is no zero and no negative in the system, so the input range is genuinely limited.

Step 1: the table, biggest first

List every value with its symbol, including the six pairs, in order from biggest to smallest:

Step 1

const NUMERALS = [
  [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'],
  [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'],
  [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'],
];
console.log(NUMERALS.length); // 13

Each entry is a small array of two items: the value and its symbol. Putting the pairs in the table is the key. The loop never needs a special rule for subtraction, because CM is just another piece it can take.

Step 2: the greedy loop

Walk the table. For each entry, add its symbol for as long as it fits:

Step 2

const NUMERALS = [
  [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'],
  [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'],
  [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'],
];
function toRoman(n) {
  let left = n;
  let out = '';
  for (const [value, symbol] of NUMERALS) {
    while (left >= value) {
      out += symbol;
      left -= value;
    }
  }
  return out;
}
console.log(toRoman(1994)); // MCMXCIV
console.log(toRoman(2026)); // MMXXVI
console.log(toRoman(40));   // XL
console.log(toRoman(3999)); // MMMCMXCIX

const [value, symbol] of NUMERALS unpacks each two-item entry into two names. The while is needed because a symbol can repeat: 2026 takes M twice and X twice.

Step 3: what happens without the pairs

Take the pairs out of the table and see what 900 and 4 turn into:

JavaScript

const PLAIN = [[1000, 'M'], [500, 'D'], [100, 'C'], [50, 'L'], [10, 'X'], [5, 'V'], [1, 'I']];
function plainRoman(n) {
  let out = '';
  for (const [value, symbol] of PLAIN) {
    while (n >= value) { out += symbol; n -= value; }
  }
  return out;
}
console.log(plainRoman(900)); // DCCCC
console.log(plainRoman(4));   // IIII

You can still read them, and old inscriptions do use forms like these, but they are not how anyone writes Roman numerals today.

Step 4: refuse what can't be written

Give the Step 2 function numbers it shouldn't accept:

JavaScript

const NUMERALS = [
  [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'],
  [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'],
  [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'],
];
function toRoman(n) {
  let left = n;
  let out = '';
  for (const [value, symbol] of NUMERALS) {
    while (left >= value) { out += symbol; left -= value; }
  }
  return out;
}
console.log(toRoman(0).length);  // 0
console.log(toRoman(-5).length); // 0
console.log(toRoman(5000));      // MMMMM

Zero and negative numbers give an empty string, with no sign that anything went wrong, and 5000 gives five Ms, which is not a real numeral. Check the input before the loop and throw a RangeError, the built-in error for "outside the range I accept":

Step 4

function checkRoman(n) {
  if (!Number.isInteger(n) || n < 1 || n > 3999) {
    throw new RangeError('Roman numerals cover 1 to 3999, not ' + n);
  }
  return n;
}
try {
  checkRoman(0);
} catch (err) {
  console.log(err.message); // Roman numerals cover 1 to 3999, not 0
}

Number.isInteger also turns away fractions like 2.5, which have no Roman form. In the full answer, this check is the first thing toRoman does.

The full solution

The answer panel has the table and toRoman with the range check, prints six numbers from 4 to 2026, and the message for zero. Its checks cover the subtractive pairs, 3999, zero and a fraction. Press Run to see the output.

The answer

// Largest first, with the six subtractive pairs sitting in their right places.
const NUMERALS = [
  [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'],
  [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'],
  [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'],
];

function toRoman(n) {
  if (!Number.isInteger(n) || n < 1 || n > 3999) {
    throw new RangeError('Roman numerals cover 1 to 3999, not ' + n);
  }
  let left = n;
  let out = '';
  for (const [value, symbol] of NUMERALS) {
    while (left >= value) {
      out += symbol;
      left -= value;
    }
  }
  return out;
}

for (const n of [4, 9, 14, 40, 1994, 2026]) console.log(String(n).padStart(4), toRoman(n));

let refused = '';
try { toRoman(0); } catch (err) { refused = err.message; }
console.log('zero:', refused);

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('four is a subtractive pair', toRoman(4), 'IV');
test('nine likewise', toRoman(9), 'IX');
test('1994', toRoman(1994), 'MCMXCIV');
test('this year', toRoman(2026), 'MMXXVI');
test('the largest expressible number', toRoman(3999), 'MMMCMXCIX');
test('forty is XL, not XXXX', toRoman(40), 'XL');
test('there is no zero', refused.includes('1 to 3999'), true);
test('and no fractions', (() => { try { toRoman(2.5); return false; } catch { return true; } })(), true);

Putting the subtractive pairs into the value table is what makes the greedy loop correct. Without [900, 'CM'], 900 would come out as DCCCC — readable, historically attested, and not what anyone means by Roman numerals today.

Unlike exercise 33's number bases, this is not a place-value system: the position of a symbol changes its meaning only through the adjacency rules, which is why there is no zero and no way to write 4,000 with these seven letters. The range check is part of the answer, not decoration.

Common mistakes

  • Leaving the six pairs out of the table. 900 becomes DCCCC and 4 becomes IIII.
  • Putting the table in the wrong order. Greedy only works biggest first. If I came first, every number would be a row of Is.
  • Using if instead of while. Then each symbol is used at most once, and 3000 comes out as M.

Try it yourself

  1. Print the Roman numerals for 1 to 20 with a loop.
  2. Write the current year in Roman numerals using new Date().getFullYear().
  3. Count how many letters the longest numeral between 1 and 3999 has, and find which number it is.

Keep practising

Newsletter

New writing, when it lands.

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