How To Generate Roman Numerals 1 To 3999 In Javascript

Have you ever wanted to learn how to generate the Roman Numerals 1 Through 3999? Well, this article does just that. This article will show you code on how to generate Roman Numerals from 1 to 3999 In JavaScript.

Image via pixabay.com

We  showed all Roman Numerals from 1 to 3999 in a previous article, but we didn’t show how to generate the code there. This article includes the code to generate Roman Numerals 1 to 3999 in 2 files: a JavaScript file and an HTML file.

The code below shows you JavaScript code that will generate all Roman Numerals from 1 to 3999 upon a user clicking on a button which says Generate Roman Numerals.”

 
function convertToRoman(num) {
  romanNumerals = [[1000,'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'],
  [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5,'V'], [4,'IV'], [1,'I']];
  result = ""
  for (var i=0; i < romanNumerals.length; i++) { while (num >= romanNumerals[i][0]) {
      num -= romanNumerals[i][0];
      result += romanNumerals[i][1];
    }
  }
  return result
}

var displayArea = document.getElementsByClassName('roman-numerals-display')[0];
var userButton = document.querySelector("button");
var romanString = ""
userButton.addEventListener("click", function() {
  for (var i=1; i < 4000; i++) {
    romanString = romanString + String(i) + " : " +  convertToRoman(i) + "\n";
  }
  displayArea.innerText = romanString;
});

The HTML code accompanying the JavaScript code above is below:

To run the file, just  have both the JavaScript and HTML files in one folder, open the index.html file, and then click on the button which says “Generate Roman Numerals”. If you would like, you can download the JavaScript code as a file called convertToRoman.js here, and you can download the HTML code called index.html here.

What did you think of this article? Did you learn much? Let’s discuss it in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *