Convert Decimal Number To Roman Number With Javascript

The roman symbol
Romans Numerals are based on the following symbols:




Basic combination :










Really big number:




How to convert from decimal to roman (less than 10000) :
function convertToRoman(num) {
 var arrRoman = [ 'I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C', 'CD','D', 'CM', 'M' ];
 var arrDec = [ 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 ];
 var romanNum = "";
 while (num > 0) {
  for (var i = 0; i < arrDec.length; i++) {
   if (num >= arrDec[arrDec.length - 1]) {
    romanNum += arrRoman[arrDec.length - 1];
    num = num - arrDec[arrDec.length - 1];
   } else {
    if (num >= arrDec[i] && num < arrDec[i + 1]) {
     romanNum += arrRoman[i];
     num = num - arrDec[i];
    }
   }
  }
 }
 return romanNum;
}

Share this

Related Posts

Previous
Next Post »