How to convert numbers to roman numerals in JavaScript
In todays post we will create an algorithm for converting a number to roman numerals. This type of problem is a common interview problem that an emloyer might want you to solve, especially in the beginning of your career.
First, let's see what a roman numeral is, and how to translate it to numbers.
What is a roman numeral?
In the table below, we have the mapping from roman numeral to their corresponding value.
There are some rules to follow as well. For example, if you want to convert the number 3 for example, you write it as III, and 15 is e.g XV. So you basically add the numbers together with the biggest to the left.
However, it is not all that simple. There are one more rule we have to follow, there can maximum be 3 of the same numerals that are following each other. Number 4 for example is written as IV since IIII is forbidden. The logic here is that the small value will substract from the higher value (5 (v) - 1 (I) = 4).
The highest possible value in roman numerals are 3999.
Let's implement our solution
We start with creating a map with our mappings from roman to their value. The reason we have 900, 400, 90, 40, 9 and 4 - is to prevent the four in a row problem. We are also defining a constant with the maximum value.
const romanToNumber = new Map(); romanToNumber.set("M", 1000); romanToNumber.set("CM", 900); romanToNumber.set("D", 500); romanToNumber.set("CD", 400); romanToNumber.set("C", 100); romanToNumber.set("XC", 90); romanToNumber.set("L", 50); romanToNumber.set("XL", 40); romanToNumber.set("X", 10); romanToNumber.set("IX", 9); romanToNumber.set("V", 5); romanToNumber.set("IV", 4); romanToNumber.set("I", 1); const MAXIMUM_NUMBER = 3999;
Now we create our logic
const numberToRoman = (number) => { // Error handling if (number > MAXIMUM_NUMBER) { throw new Error(`Number is to high. Max is ${MAXIMUM_NUMBER}`); } else if (number < 1) { throw new Error("Number must be greater than 0"); } let result = ""; // value is the current value from the romanToNumber map, and roman is the roman numeral representation romanToNumber.forEach((value, roman) => { // If the number is still bigger than the current roman value, we keep on substracting and adding the letter to the "result" variable. while (number >= value) { // Substracting value from number number -= value; // Adding roman numerals to the final result string result += roman; } }); // returning the final result return result; };
Let's try it out
console.log(numberToRoman(6)); // VI console.log(numberToRoman(987)); // CMLXXXVII console.log(numberToRoman(321)); // CCCXXI console.log(numberToRoman(456)); // CDLVI
Outro
In this guide, we solved the conversion between numbers and roman numerals. The actual logic is quite straight forward as long as you know the rules that should apply - as with most of the problems we face in our daily jobs :)
I hope you found this post helpful, and have a great day!