Emmanuel Akinfulubi

JavaScriptMath

Roman numeral converter both ways in JavaScript

Intermediate · 4 min read

Roman numerals still turn up on clock faces, in film credits, in book chapters and in the names of kings and sporting events. Converting them is a classic programming exercise because it has two halves that feel different: writing a numeral is a matter of choosing, and reading one is a matter of looking ahead.

In this tutorial you will write toRoman and fromRoman, prove that converting there and back works for every number from 1 to 3999, and then find two strings that the reader happily accepts even though they are not proper numerals. You will finish with a short validator that catches them. You need to know for loops, arrays and objects.

How Roman numerals work

There are seven letters:

Output

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

Normally you write the biggest letters first and add them up: MMXXIV is 1000 + 1000 + 10 + 10 + 4 = 2024.

The twist is subtraction. A smaller letter in front of a bigger one is taken away. IV is 5 - 1 = 4, and XC is 100 - 10 = 90. Only six pairs are used: IV (4), IX (9), XL (40), XC (90), CD (400) and CM (900).

The greedy idea

To write a number, keep taking the biggest value that still fits. For 1994: take M (1000), 994 is left. Take CM (900), 94 left. Take XC (90), 4 left. Take IV (4). The result is MCMXCIV. This method of always grabbing the biggest piece is called a greedy algorithm.

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

92 Roman numerals, out and back

fair

Convert a number to a Roman numeral and back. Prove the round trip holds for every value from 1 to 3999, then show that your reader happily accepts IIII and IC, and write the validator that catches them.

Stuck? Three hints, smallest first
  1. 1. Put the four subtractive pairs — CM, CD, XC, XL, IX, IV — into the value table and greedy works.
  2. 2. Reading back: a letter smaller than the one after it counts as negative.
  3. 3. To check a numeral is well formed, render its value again and compare the strings.

Step 1: a table with the pairs in it

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'],
];

Each entry is a value and its letters, biggest first. The six subtraction pairs are listed as values of their own. That is the whole trick: with them in the table, greedy never has to think about subtraction.

Step 2: the greedy writer

Step 2

const greedy = (table) => (n) => {
  let out = '';
  let left = n;
  for (const [value, letters] of table) {
    while (left >= value) {
      out += letters;
      left -= value;
    }
  }
  return out;
};
const toRoman = greedy(NUMERALS);
console.log([1, 4, 9, 14, 40, 90, 400].map(toRoman).join(' ')); // I IV IX XIV XL XC CD
console.log(toRoman(1994), toRoman(2024), toRoman(3999));       // MCMXCIV MMXXIV MMMCMXCIX

greedy takes a table and returns a converter function. For each row, the while loop adds those letters as many times as the value fits, then moves to the next row.

Step 3: the wrong turn, no pairs

What if you leave the pairs out?

Step 3

const PLAIN = [[1000, 'M'], [500, 'D'], [100, 'C'], [50, 'L'], [10, 'X'], [5, 'V'], [1, 'I']];
const toRomanPlain = greedy(PLAIN);
console.log(toRomanPlain(9), toRomanPlain(1994)); // VIIII MDCCCCLXXXXIIII

It still adds up, but it reads like a tally: 9 is VIIII, not IX. Old carvings sometimes look like this, but it is not the modern form.

Step 4: the reader

To read a numeral, go left to right. If a letter is smaller than the one after it, subtract it. Otherwise, add it.

Step 4

const LETTER = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
const fromRoman = (s) => {
  let total = 0;
  for (let i = 0; i < s.length; i++) {
    const here = LETTER[s[i]];
    const next = i + 1 < s.length ? LETTER[s[i + 1]] : 0;
    total += here < next ? -here : here;
  }
  return total;
};
console.log(fromRoman('MCMXCIV'), fromRoman('MMMCMXCIX')); // 1994 3999

In MCMXCIV, the first C is followed by M, so it counts as -100, and the M after it adds 1000: together, 900. The last letter has nothing after it, so next is 0 and it is always added.

Step 5: prove the round trip

Step 5

const roundTripHolds = (limit) => {
  for (let n = 1; n <= limit; n++) if (fromRoman(toRoman(n)) !== n) return false;
  return true;
};
console.log(roundTripHolds(3999)); // true

Every number from 1 to 3999 converts to a numeral and back to itself. 3999 is the biggest you can write with the standard letters, since there is no letter for 5000.

Step 6: the reader is too kind

Step 6

console.log(fromRoman('IIII'), fromRoman('IC')); // 4 99

IIII is not how you write 4, and IC is not how you write 99 (that is XCIX). But the reader gives both a value. It turns any string of those seven letters into a number, proper or not.

Step 7: the validator

You already have a writer that only produces proper numerals. So read the string, write the value back out, and see whether you get the same string.

Step 7

const isCanonical = (s) => s.length > 0 && toRoman(fromRoman(s)) === s;
console.log(isCanonical('MCMXCIV'), isCanonical('IIII'), isCanonical('IC')); // true false false

IIII reads as 4, and 4 writes as IV, which doesn't match. Canonical just means "the one standard way of writing it". This trick works far beyond Roman numerals: whenever you have a strict writer and a loose reader, write(read(s)) === s checks that the input is well formed.

Step 8: zero and negatives

Step 8

console.log(JSON.stringify(toRoman(0)), JSON.stringify(toRoman(-5))); // "" ""

There is no Roman numeral for 0 or negative numbers. No value in the table fits, so the loop adds nothing and returns an empty string. JSON.stringify shows the empty string with its quotes, so you can see it.

The full solution

The answer panel has the table, greedy, toRoman, toRomanPlain, fromRoman, isCanonical and the round-trip check, and also finds the longest numeral below 4000: MMMDCCCLXXXVIII for 3888, 15 letters. Press Run to see the output.

The answer

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'],
];
const PLAIN = [[1000, 'M'], [500, 'D'], [100, 'C'], [50, 'L'], [10, 'X'], [5, 'V'], [1, 'I']];

const greedy = (table) => (n) => {
  let out = '';
  let left = n;
  for (const [value, letters] of table) {
    while (left >= value) {
      out += letters;
      left -= value;
    }
  }
  return out;
};

const toRoman = greedy(NUMERALS);
const toRomanPlain = greedy(PLAIN);

const LETTER = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };

const fromRoman = (s) => {
  let total = 0;
  for (let i = 0; i < s.length; i++) {
    const here = LETTER[s[i]];
    const next = i + 1 < s.length ? LETTER[s[i + 1]] : 0;
    total += here < next ? -here : here;
  }
  return total;
};

const isCanonical = (s) => s.length > 0 && toRoman(fromRoman(s)) === s;

const roundTripHolds = (limit) => {
  for (let n = 1; n <= limit; n++) if (fromRoman(toRoman(n)) !== n) return false;
  return true;
};

const longestUnder4000 = (() => {
  let best = '';
  for (let n = 1; n < 4000; n++) {
    const r = toRoman(n);
    if (r.length > best.length) best = r;
  }
  return best;
})();

console.log('small numbers :', [1, 4, 9, 14, 40, 90, 400].map(toRoman));
console.log('1994, 3999    :', toRoman(1994), toRoman(3999));
console.log('without pairs :', toRomanPlain(9), toRomanPlain(1994));
console.log('read back     :', fromRoman('MCMXCIV'), fromRoman('MMMCMXCIX'));
console.log('nonsense      :', fromRoman('IIII'), fromRoman('IC'));
console.log('canonical?    :', isCanonical('MCMXCIV'), isCanonical('IIII'), isCanonical('IC'));
console.log('zero, negative:', JSON.stringify(toRoman(0)), JSON.stringify(toRoman(-5)));
console.log('longest       :', longestUnder4000, longestUnder4000.length, 'which is', fromRoman(longestUnder4000));

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 small numbers, including the four subtractive pairs', [1, 4, 9, 14, 40, 90, 400].map(toRoman), ['I', 'IV', 'IX', 'XIV', 'XL', 'XC', 'CD']);
test('1994, 2024 and the largest classical numeral', [toRoman(1994), toRoman(2024), toRoman(3999)], ['MCMXCIV', 'MMXXIV', 'MMMCMXCIX']);
test('drop the pairs and greedy still terminates, it just reads like a tally', [toRomanPlain(9), toRomanPlain(1994)], ['VIIII', 'MDCCCCLXXXXIIII']);
test('reading back works by comparing each letter with the one after it', [fromRoman('MCMXCIV'), fromRoman('MMMCMXCIX')], [1994, 3999]);
test('and the round trip holds for every number from 1 to 3999', roundTripHolds(3999), true);
test('but the reader accepts what Rome would not: IIII is 4 and IC is 99', [fromRoman('IIII'), fromRoman('IC')], [4, 99]);
test('so validating means rendering the value again and comparing strings', [isCanonical('MCMXCIV'), isCanonical('IIII'), isCanonical('IC')], [true, false, false]);
test('zero and negatives have no numeral, and the loop returns an empty string', [toRoman(0), toRoman(-5)], ['', '']);
test('the longest numeral below 4000 belongs to 3888, at fifteen letters', [longestUnder4000, longestUnder4000.length, fromRoman(longestUnder4000)], ['MMMDCCCLXXXVIII', 15, 3888]);

Writing a numeral is a greedy algorithm, and greedy is provably correct here for one reason: the subtractive pairs are in the table. With CM, CD, XC, XL, IX and IV listed as values of their own, always taking the largest that fits can never paint you into a corner. Drop them and the algorithm still works, it just produces MDCCCCLXXXXIIII for 1994 — which is a legal tally, and is what the Romans themselves often carved.

Reading a numeral is the mirror image: scan left to right, and any letter smaller than its right-hand neighbour counts negative. Three lines, no table of pairs needed. The catch is that it is a reader, not a parser — it assigns a number to any string of those seven letters, so IIII is 4 and IC is 99. Neither is a well-formed numeral.

The validator is the idea worth keeping beyond Roman numerals. When you have a canonical writer and a lenient reader, write(read(s)) === s is a complete well-formedness check for free, and it stays correct as the writer changes. The same pattern validates ISO dates, normalised URLs and JSON round trips.

Common mistakes

  • Leaving the subtraction pairs out of the table. You get tally numerals like VIIII. Put all six pairs in, in size order.
  • Treating the reader as a validator. fromRoman('IC') is 99. Check with toRoman(fromRoman(s)) === s.
  • Forgetting the last letter. When looking ahead, the last letter has no neighbor. Use 0 as its "next" so it is always added.

Try it yourself

  1. Make fromRoman accept lowercase input like 'mmxxiv'.
  2. Change toRoman to throw an error for 0, negatives, decimals and anything above 3999.
  3. Count how many numbers from 1 to 3999 have a numeral longer than 10 letters.

Keep practising

Newsletter

New writing, when it lands.

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