Roman Numeral Converter: how it works and how to build one
Convert numbers to Roman numerals and back. This guide explains what happens behind the button and shows the code, so you can build your own.
What it does
Converts whole numbers from 1 to 3999 to Roman numerals and checks that Roman numerals are written correctly when converting back.
When to use it
- Clock faces and book chapters
- Movie and event years
- Homework
How to use it
- Choose the direction.
- Paste one value per line.
- Copy the result.
Try it free in your browser, nothing is uploaded: https://eskillsfy.com/tools/roman-numerals
How it works
Roman numerals add symbol values (M=1000, D=500, C=100 …) but use subtraction for 4 and 9 (IV, IX, XL, XC, CD, CM). Converting to Roman is a greedy loop over a table that includes those pairs: take the biggest value that fits, repeat.
Converting back is the same table, read from the left. A regex checks the numeral is well-formed first.
Build it yourself
Here is the core of the tool. It has no dependencies unless noted, so you can paste it into any TypeScript or JavaScript project.
roman.ts (ts)
const TABLE: [number, string][] = [[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"]];
export function toRoman(n: number) {
if (!Number.isInteger(n) || n < 1 || n > 3999) throw new Error("1 to 3999 only");
let out = "";
for (const [v, r] of TABLE) while (n >= v) { out += r; n -= v; }
return out;
}
export function fromRoman(s: string) {
let n = 0, i = 0;
for (const [v, r] of TABLE) while (s.startsWith(r, i)) { n += v; i += r.length; }
return n;
}
Make it production-ready
- Validate with /^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/.
Questions
Why only up to 3999?
Standard Roman numerals have no symbol above M (1000), so 3999 (MMMCMXCIX) is the largest.
Free, runs in your browser, nothing is uploaded.