How to convert a decimal number to roman using JavaScript?

JavascriptWeb DevelopmentFront End Technology

To convert a decimal number to roman, try to run the following JavaScript code −

Example

Live Demo

<!DOCTYPE html>
<html>
   <body>
      <script>
         // roman numeral
         var romanNum = new Array();
         romanNum = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
         // decimal number
         var dNum = new Array();
         dNum = [1000,900,500,400,100,90,50,40,10,9,5,4,1];
         function decimalRoman(value) {
            if (value <= 0 || value >= 4000)
               return value;
               var romanNumeral = "";
            for (var i = 0; i<romanNum.length; i++) {
               while (value >= dNum[i]) {
                  value -= dNum[i];
                  romanNumeral += romanNum[i];
               }
            }
            return romanNumeral;
         }
         document.write(decimalRoman(39));
         document.write("<br>"+decimalRoman(145));
         document.write("<br>"+decimalRoman(520));
      </script>
   </body>
</html>

Output

XXXIX
CXLV
DXX
raja
Published on 03-Feb-2018 17:52:27
Advertisements