Converting Roman numerals into decimal in JavaScript
Converting Roman numerals into decimal is a fun little problem to solve. Getting the solution is dependent on knowing the rules of Roman numerals, and they’re actually simpler than you might think:
- All letters directly map to an integer value.
- A letter followed by a letter of higher value is subtracted.
- All other letters are added.
Before I looked this up, I thought that the rules were more complicated, e.g. with multiplication in certain situations (which is how Chinese numerals work).
Based on the actual ruleset, though, we just need to iterate with a look-ahead of 1 to find the negative values:
const romanMap = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
function parseRoman(roman) {
let sum = 0;
for (let i = 0; i < roman.length; i++) {
const current = romanMap[roman[i]];
const next = romanMap[roman[i + 1]];
if (next === undefined) {
sum += current;
continue;
}
if (current >= next) {
sum += current;
continue;
}
sum -= current;
}
return sum;
}
There’s a little JavaScript gotcha here, which is that a traditional for loop
works, but a for ... in
loop does not; it’s not possible to look at other
values from within the for ... in
loop.