Skip to content

Instantly share code, notes, and snippets.

@J2D2Development
Created July 22, 2017 03:41
Show Gist options
  • Save J2D2Development/1e7fd1e671a9c41588f6f9841f7511af to your computer and use it in GitHub Desktop.
Save J2D2Development/1e7fd1e671a9c41588f6f9841f7511af to your computer and use it in GitHub Desktop.
const conversions = {
0: '', 1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V',
6: 'VI', 7: 'VII', 8: 'VIII', 9: 'IX', 10: 'X',
20: 'XX', 30: 'XXX', 40: 'XL', 50: 'L', 60: 'LX',
70: 'LXX', 80: 'LXXX', 90: 'XC', 100: 'C', 200: 'CC',
300: 'CCC', 400: 'CD', 500: 'D', 600: 'DC', 700: 'DCC',
800: 'DCCC', 900: 'CM', 1000: 'M', 2000: 'MM', 3000: 'MMM'
};
function convertToRoman(num) {
const numArray = String(num).split('');
const len = numArray.length;
const ones = conversions[Number(numArray[numArray.length - 1])];
let thousands, hundreds, tens;
let ans = '';
switch(len) {
case 1:
ans = ones;
break;
case 2:
tens = numArray[0] + '0';
ans = conversions[Number(tens)] + ones;
break;
case 3:
hundreds = numArray[0] + '00';
tens = numArray[1] + '0';
ans = conversions[Number(hundreds)] + conversions[Number(tens)] + ones;
break;
case 4:
thousands = numArray[0] + '000';
hundreds = numArray[1] + '00';
tens = numArray[2] + '0';
ans = conversions[Number(thousands)] + conversions[Number(hundreds)] + conversions[Number(tens)] + ones;
break;
default:
ans = 'Cannot find roman numeral equivelent';
break;
}
return ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment