Convert Roman numerals to a number in JavaScript
Intermediate · 3 min read
Going from Roman numerals back to a number is the other half of a converter. You need it to read chapter numbers, copyright years in film credits, or any data typed in as XIV instead of 14.
In this tutorial you will write fromRoman(text), which reads MCMXCIV as 1994. It needs only a lookup table and one comparison. Then you will feed it IIII and see why reading a numeral is a different job from checking that it is written correctly. You need to know what an object is, how a for loop with an index works, and what ?? does (it gives a fallback when a value is undefined or null).
The seven symbols
I = 1 V = 5 X = 10 L = 50 C = 100 D = 500 M = 1000
Most of the time you just add the symbols up: MMXXVI is 1000 + 1000 + 10 + 10 + 5 + 1 = 2026.
The subtraction rule in one sentence
When a symbol is worth less than the one right after it, subtract it instead of adding it.
IV: I (1) is less than V (5), so it counts as -1. Then V adds 5. Total: 4.
MCMXCIV, letter by letter:
M 1000 next is C (100), not bigger -> +1000
C 100 next is M (1000), bigger -> -100
M 1000 next is X (10) -> +1000
X 10 next is C (100), bigger -> -10
C 100 next is I (1) -> +100
I 1 next is V (5), bigger -> -1
V 5 nothing after it -> +5
total 1994
That one comparison covers all six pairs (IV, IX, XL, XC, CD, CM) without listing them.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
73 Roman numerals back to a number
fairRead MCMXCIV back as 1994. Then check what your reader does with IIII, and decide whether that matters.
Stuck? Three hints, smallest first
- 1. Walk the letters left to right with a lookup table of the seven values.
- 2. If a symbol is smaller than the one after it, subtract it instead of adding.
- 3. Reading is not validating: a permissive reader will happily accept strings no Roman ever wrote.
Step 1: a lookup table
An object maps each letter to its value:
const VALUE = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
console.log(VALUE['X']); // 10
console.log(VALUE['Z']); // undefined
A letter that isn't in the table gives undefined. Keep that in mind for later.
Step 2: add or subtract each letter
Walk the letters with an index, so you can look at the next one too:
const VALUE = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
function fromRoman(text) {
const letters = text.toUpperCase().split('');
let total = 0;
for (let i = 0; i < letters.length; i++) {
const here = VALUE[letters[i]];
const next = VALUE[letters[i + 1]] ?? 0;
total += here < next ? -here : here;
}
return total;
}
console.log(fromRoman('IV')); // 4
console.log(fromRoman('MCMXCIV')); // 1994
console.log(fromRoman('mmxxvi')); // 2026
split('') turns the text into an array of single letters. toUpperCase() first means lower-case input works too.
On the last letter, letters[i + 1] is past the end, so VALUE[...] is undefined. ?? 0 turns that into 0, and nothing is less than 0, so the last letter is always added.
here < next ? -here : here is the rule from above: subtract when smaller than the next, add otherwise.
Step 3: refuse letters that aren't numerals
Try a stray letter with the Step 2 version:
const VALUE = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
const letters = 'MZ'.split('');
console.log(VALUE[letters[1]]); // undefined
console.log(1000 + VALUE[letters[1]]); // NaN
Z has no value, and adding undefined gives NaN ("Not a Number"). Check every letter before you start, and throw a TypeError if one isn't in the table:
const VALUE = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
const letters = 'MZ'.split('');
try {
if (letters.some((ch) => !(ch in VALUE))) throw new TypeError('not a numeral: MZ');
} catch (err) {
console.log(err.message); // not a numeral: MZ
}
some returns true if any letter passes the test. ch in VALUE asks whether the object has that key. In the full answer this check sits at the top of fromRoman.
Step 4: reading is not checking
Feed in strings nobody would write:
const VALUE = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
function fromRoman(text) {
const letters = text.toUpperCase().split('');
let total = 0;
for (let i = 0; i < letters.length; i++) {
const here = VALUE[letters[i]];
const next = VALUE[letters[i + 1]] ?? 0;
total += here < next ? -here : here;
}
return total;
}
console.log(fromRoman('IIII')); // 4
console.log(fromRoman('IVI')); // 5
Both give an answer. fromRoman reads a numeral; it doesn't check that the numeral is written correctly. If you need to reject badly formed input, the simplest test is to convert the number back with toRoman (from the previous exercise) and compare: toRoman(4) is 'IV', not 'IIII', so IIII fails.
The full answer uses that same round trip to check all 3,999 numbers: every one of them turned into a numeral and back gives the number it started with.
The full solution
The answer panel has the table and fromRoman with the letter check, reads five numerals, then converts every number from 1 to 3999 to Roman and back. Its checks include lower case, IIII, IVI and a stray letter. Press Run to see the output.
const VALUE = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
function fromRoman(text) {
const letters = text.toUpperCase().split('');
if (letters.some((ch) => !(ch in VALUE))) throw new TypeError('not a numeral: ' + text);
let total = 0;
for (let i = 0; i < letters.length; i++) {
const here = VALUE[letters[i]];
const next = VALUE[letters[i + 1]] ?? 0;
total += here < next ? -here : here; // smaller before larger means subtract
}
return total;
}
for (const r of ['IV', 'IX', 'XL', 'MCMXCIV', 'MMXXVI']) console.log(r.padEnd(9), fromRoman(r));
// Same table as exercise 72, so a round trip can be checked.
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 toRoman = (n) => NUMERALS.reduce((out, [v, s]) => { while (n >= v) { out += s; n -= v; } return out; }, '');
const roundTrips = Array.from({ length: 3999 }, (_, i) => i + 1).every((n) => fromRoman(toRoman(n)) === n);
console.log('every number from 1 to 3999 round-trips:', roundTrips);
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.
test('a subtractive pair', fromRoman('IV'), 4);
test('the long one', fromRoman('MCMXCIV'), 1994);
test('this year', fromRoman('MMXXVI'), 2026);
test('lower case is accepted', fromRoman('mmxxvi'), 2026);
test('every number from 1 to 3999 survives the round trip', roundTrips, true);
test('but IIII also reads as four, though nobody writes it', fromRoman('IIII'), 4);
test('and so does the nonsense IVI read as five', fromRoman('IVI'), 5);
test('a stray letter is refused', (() => { try { fromRoman('MZ'); return false; } catch { return true; } })(), true);
The subtractive rule is one comparison: if this symbol is worth less than the next one, it counts against the total. That single line handles all six pairs without listing them.
fromRoman('IIII') answering 4 is the lesson. Parsing and validating are different jobs, and a reader built from a lookup table accepts plenty of strings that are not well-formed numerals. If you need to reject them, the cheapest honest test is to convert back — toRoman(fromRoman(text)) === text.toUpperCase() — which is exactly what the round-trip assertion does across the whole range.
Common mistakes
- Comparing with the previous letter instead of the next. The rule looks ahead: a letter is subtracted when the one after it is bigger.
- Forgetting
toUpperCase(). The table only has capital letters, so every letter of'xiv'would look upundefined. - Treating a successful read as valid input.
IIIIreads as 4. Check with a round trip if it matters.
Try it yourself
- Read
XLII,CDXLIVandMMMCMXCIX, and work each one out by hand first. - Write
isValidRoman(text)usingfromRomanand thetoRomanfrom the previous exercise. - Change
fromRomanto ignore spaces, so'MM XXVI'reads as 2026.