Convert Values to Roman Numerals in Google Sheets with Custom Formula

Convert a number to its Roman numeral equivalent

function TO_ROMAN(num){

 if(typeof num !== ‘number’) return NaN;

 let roman = ”;

 const romanValues = {

   M: 1000,

   CM: 900,

   D: 500,

   CD: 400,

   C: 100,

   XC: 90,

   L: 50,

   XL: 40,

   X: 10,

   IX: 9,

   V: 5,

   IV: 4,

   I: 1

 };

 for(let key in romanValues){

   while(num >= romanValues[key]){

     roman += key;

     num -= romanValues[key];

   }

 }

 return roman;

}

The provided code defines a function called TO_ROMAN that takes a parameter num and converts it to a Roman numeral representation. Here is a detailed explanation of how the function works:

  1. if(typeof num !== ‘number’) return NaN; checks if the num parameter is not a number. If it is not a number, the function immediately returns NaN (Not a Number). This is a basic input validation step to ensure that the input is a valid number.
  2. let roman = ”; creates an empty string variable called roman, which will store the Roman numeral representation of the input number.
  3. const romanValues = {…}; declares a constant object called romanValues that maps Roman numerals to their corresponding decimal values. This mapping is used to convert the input number to its Roman numeral representation. The object stores the Roman numerals as keys and their corresponding decimal values as values.
  4. The for…in loop iterates over each key in the romanValues object.
  5. Inside the loop, the while loop is used to check if the input number (num) is greater than or equal to the current Roman numeral’s decimal value (romanValues[key]).
  6. If the condition is true, it means that the current Roman numeral should be added to the roman string. So, roman += key; concatenates the current Roman numeral (key) to the roman string.
  7. Additionally, num -= romanValues[key]; subtracts the decimal value of the current Roman numeral from the num variable. This ensures that we keep track of the remaining value that needs to be converted into Roman numerals.
  8. The loop continues until the num variable is less than the decimal value of the current Roman numeral, at which point it moves to the next Roman numeral in the romanValues object.
  9. Once all the Roman numerals have been processed and appended to the roman string, the function exits the loop.
  10. Finally, the function returns the roman string, which represents the Roman numeral representation of the input number.

In summary, this function converts a decimal number into its Roman numeral representation by iteratively subtracting the decimal values of Roman numerals from the input number and appending the corresponding Roman numerals to a string.

Input (num)
1I
3III
4IV
9IX
10X
14XIV
50L
44XLIV
2023MMXXIII
33XXXIII