Last month I had to import a legacy product catalog where every model year was stored as a Roman numeral: MMXXVI, XIX, MCMXCIV, and one row that just said IIII. My first instinct was a ten-line Python function. It handled the test rows fine, then fell over in three separate ways on the real data. If you've ever had to parse a copyright line, a Super Bowl title, or an old building plaque programmatically, you've probably met the same problems.
Here are the shortest correct implementations I could write in Python and JavaScript, plus the traps that bit me.
Method 1: Python 3.11, greedy subtraction
The standard trick is a value table ordered from largest to smallest. Walk it once, and subtractive forms like CM fall out for free because 900 sits in the table as its own entry.
# Python 3.11.8 ROMAN = [ (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"), ] def to_roman(n: int) -> str: if isinstance(n, bool) or not isinstance(n, int): raise TypeError(f"expected int, got {type(n).__name__}") if not 1 <= n <= 3999: raise ValueError(f"out of range 1..3999: {n}") out = [] for value, numeral in ROMAN: count, n = divmod(n, value) out.append(numeral * count) return "".join(out) import re ROMAN_RE = re.compile( r"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$" ) VALUES = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def from_roman(s: str) -> int: t = s.strip().upper() if not ROMAN_RE.match(t): raise ValueError(f"invalid roman numeral: {s!r}") total = 0 for i, ch in enumerate(t): v = VALUES[ch] if i + 1 < len(t) and VALUES[t[i + 1]] > v: total -= v else: total += v return total In the REPL this looks like:
>>> to_roman(2026) 'MMXXVI' >>> from_roman("mcmxciv") 1994 >>> to_roman(4000) ValueError: out of range 1..3999: 4000 >>> from_roman("IC") ValueError: invalid roman numeral: 'IC' That range check on line 8 of to_roman is not decoration. Strict subtractive notation tops out at 3999, and Roman numerals have no way to write zero at all. The Wikipedia article on Roman numerals covers the medieval workarounds (the letter N, the vinculum) if you're curious, but no modern library supports them consistently, so I reject instead of guessing.
Method 2: Node.js 22, same algorithm, one extra trap
The JavaScript port is almost line-for-line identical:
// Node 22.13.0 const ROMAN = [ [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 ROMAN_RE = /^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/; const VALUES = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }; function toRoman(n) { if (!Number.isInteger(n) || n < 1 || n > 3999) throw new RangeError(`expected integer 1..3999, got ${n}`); let out = ""; for (const [value, numeral] of ROMAN) { while (n >= value) { out += numeral; n -= value; } } return out; } function fromRoman(s) { const t = s.trim().toUpperCase(); if (!ROMAN_RE.test(t)) throw new SyntaxError(`invalid roman numeral: ${s}`); let total = 0; for (let i = 0; i < t.length; i++) { const v = VALUES[t[i]]; const next = VALUES[t[i + 1]] ?? 0; total += next > v ? -v : v; } return total; } console.log(toRoman(1994)); // MCMXCIV console.log(fromRoman("MMXXVI")); // 2026 Watch the RangeError guard in toRoman. My first draft omitted it, and a quick round-trip test caught the consequence immediately:
> assert.strictEqual(toRoman(0), String(0)) Uncaught AssertionError [ERR_ASSERTION]: '' == '0' With no guard, toRoman(0) doesn't crash — it quietly returns an empty string, because the while (n >= value) loop never runs. An empty string flowing into a CSV import looks exactly like a missing value, which is a much nastier bug to trace than an exception. The regex in fromRoman is a standard strict pattern; if you want a refresher on how alternation and anchors behave in JavaScript, the MDN regular expressions guide is the reference I keep open while writing these.
Method 3: just use a browser tool
For one-off conversions — a plaque in a photo, a film copyright line, checking what year MCMXCIV actually is — I stopped writing scripts entirely. I open a free online roman numeral converter on utilvy, paste either side of the conversion, and read the result. It runs entirely in the browser, so there's nothing to install and no data leaves the tab, and it converts in both directions with a single click.
This matters more than it sounds. Half the time my "quick script" needs are really verification needs: is MMXXVI 2026? Does this vendor really ship "XI units" or is the invoice OCR mangled? Pasting into this browser-based converter answers in two seconds what a REPL would take thirty, and it validates input instead of silently accepting garbage like a naive parser would.
Three traps that bit me
1. IC is not 99. You can only subtract powers-of-ten one step down: IX (9), XC (90), CM (900). Writing 99 as IC looks clever and parses under a lenient "subtract when smaller" rule, giving you exactly 99 — and then a strict system downstream rejects it. The correct form is XCIX. My parser accepts IC if I drop the regex and rely only on the additive/subtractive loop, so the regex check stays in, always:
>>> from_roman("IC") ValueError: invalid roman numeral: 'IC' >>> from_roman("XCIX") 99 2. Clock faces use IIII, not IV. Traditional watch and clock dials spell 4 as IIII — a watchmaker convention old enough that nobody agrees on its origin, and visible on the iconic Big Ben face. My strict regex rejects it: from_roman("IIII") throws ValueError: invalid roman numeral: 'IIII'. That's exactly the row in my product catalog that broke the import. When additive forms are plausible input, I relax the last group of the pattern to V?I{0,3}|IIII and normalize on the way in.
3. Zero, negatives, and anything above 3999. Every strict implementation I've seen enforces the 1–3999 band, and for good reason: there's no zero, negative numerals don't exist, and 4000+ needs overline notation that plain text can't carry. The Python roman package (version 3.3 on PyPI) throws a clear OutOfRangeError: Number out of range (must be 1..3999), but a hand-rolled JavaScript loop can return '' for zero with no error at all — the silent failure I showed in Method 2. Validate the band before you loop, not after.
Quick reference
| Task | Best tool | Watch out for |
|---|---|---|
| Batch conversion in a pipeline | Python to_roman / from_roman | Range guard 1–3999, reject IC-style shortcuts |
| Node/browser code | Same algorithm in JS | toRoman(0) returns '' without a guard |
| One-off checks | Online converter | Lenient parsers accept invalid forms |
Legacy data with IIII | Relaxed regex variant | Watchmaker additive notation |
The core of all of this is small: one value table, one strict regex, one range check. Get those three right and Roman numerals stop being a surprise. And when it's a single value rather than a dataset, I skip the code and use the Roman Numeral Converter on utilvy directly — then get back to the actual work.
More free browser-based utilities at utilvy.com.
