HomeUncategorisedBuilding a Roman Numeral Converter with JavaScript

Building a Roman Numeral Converter with JavaScript

Roman numerals have a unique charm and are still used today in various contexts, from numbering movie sequels to marking historic events. In this blog post, we’ll explore how to create a Universal Roman Numeral Converter using HTML, CSS, and JavaScript. This tool can convert numbers (1–3999) to Roman numerals and vice versa.

Features of the Converter

  1. Two-Way Conversion
    • Convert numbers (e.g., 1987) into Roman numerals (MCMLXXXVII).
    • Convert Roman numerals (e.g., MCMLXXXVII) back into numbers (1987).
  2. Validation
    • Handles invalid inputs gracefully.
    • Ensures numbers are between 1 and 3999, the range supported by Roman numerals.
  3. Responsive Design
    • A simple and user-friendly interface that works seamlessly on any device.

Video Tutorial:

1. HTML Structure

The HTML provides the skeleton for the converter, including an input field, a button, and a display area for results.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Roman Numeral Converter</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <h1>Universal Number <-> Roman Numeral Converter</h1>
      <label for="input">Enter a Number(1-3999) or a Roman Numeral:</label>
      <div class="input-block">
        <input type="text" id="input" placeholder="e.g., 1987 or MCMXXXVII" />
        <button onclick="convertInput()">Convert</button>
      </div>
      <div class="result" id="result"></div>
    </div>
    <script src="script.js"></script>
  </body>
</html>

2. CSS for Styling

The CSS ensures the interface is visually appealing and responsive, with a gradient background and styled input elements.

body {
  height: 100vh;
  background: linear-gradient(to bottom, #ffd55c 50%, #5a94ff 50%);
}
.container {
  background-color: #ffffff;
  width: min(600px, 90vw);
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  padding: 20px;
  border-radius: 10px;
}
h1 {
  font-size: 25px;
  text-align: center;
}
.input-block {
  display: flex;
  justify-content: center;
  gap: 10px;
}
input,
button {
  padding: 10px;
  margin: 10px 0;
  font-size: 16px;
  border-radius: 5px;
}

3. JavaScript Logic

The JavaScript provides the logic for converting between numbers and Roman numerals.

Number to Roman Conversion

function numberToRoman(num) {
  const romanNumerals = [
    { value: 1000, numeral: "M" },
    { value: 900, numeral: "CM" },
    { value: 500, numeral: "D" },
    { value: 400, numeral: "CD" },
    { value: 100, numeral: "C" },
    { value: 90, numeral: "XC" },
    { value: 50, numeral: "L" },
    { value: 40, numeral: "XL" },
    { value: 10, numeral: "X" },
    { value: 9, numeral: "IX" },
    { value: 5, numeral: "V" },
    { value: 4, numeral: "IV" },
    { value: 1, numeral: "I" },
  ];
  let result = "";
  for (const { value, numeral } of romanNumerals) {
    while (num >= value) {
      result += numeral;
      num -= value;
    }
  }
  return result;
}

Roman to Number Conversion

function romanToNumber(roman) {
  const romanToNum = {
    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,
  };
  let i = 0;
  let num = 0;
  while (i < roman.length) {
    const twoChar = roman[i] + (roman[i + 1] || "");
    if (romanToNum[twoChar]) {
      num += romanToNum[twoChar];
      i += 2;
    } else {
      num += romanToNum[roman[i]];
      i++;
    }
  }
  return num;
}
function convertInput() {
  const input = document.getElementById("input").value.trim().toUpperCase();
  const validRoman = /^[MDCLXVI]+$/; 
  const resultDiv = document.getElementById("result");

  if (!input) {
    resultDiv.textContent = "Please enter a value.";
    return;
  }

  if (!isNaN(input)) {
    const num = parseInt(input, 10);
    if (num < 1 || num > 3999) {
      resultDiv.textContent = "Please enter a number between 1 and 3999.";
    } else {
      const roman = numberToRoman(num);
      resultDiv.textContent = `Number ${num} in Roman numerals is: ${roman}`;
    }
  } else if (validRoman.test(input)) {
    try {
      const number = romanToNumber(input);
      resultDiv.textContent = `Roman numeral ${input} equals: ${number}`;
    } catch {
      resultDiv.textContent = "Invalid Roman numeral.";
    }
  } else {
    resultDiv.textContent = "Please enter a valid number or Roman numeral.";
  }
}

Conclusion:

With this Roman Numeral Converter, you now have a fun and practical way to understand how Roman numerals and numbers relate. Feel free to customize the code to suit your needs or extend it further. Happy coding! 🎉

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

fifteen + 18 =

Most Popular