How to Convert Number to Roman using JavaScript

numbertoroman

Introduction

Roman numerals have a unique historical significance, and creating a converter to translate modern numbers into Roman numerals can be a fascinating and practical addition to a website. In this blog post, we’ll guide you through the process of building a Roman Numeral Converter using HTML, CSS, and JavaScript.

HTML Structure

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Roman Numeral Converter</title>
    <link
      href="https://fonts.googleapis.com/css2?family=Rubik:wght@400;600&display=swap"
      rel="stylesheet"
    />
  </head>
  <body>
    <div class="conversion-container">
      <div class="input-section">
        <input
          type="number"
          id="input-number"
          placeholder="Enter Number Here..."
          class="input-field"
        />
        <button type="submit" id="convert-button" class="convert-button">
          Convert
        </button>
      </div>
      <p id="converted-result">
        <span>Enter The Number & Hit Convert</span>
      </p>
      <p id="error-message"></p>
    </div>
  </body>
</html>
HTML

Explanation:

  • <input type="number" id="input-number" placeholder="Enter Number Here..." class="input-field">: An input field where users can enter the number they want to convert.
  • <button type="submit" id="convert-button" class="convert-button">Convert</button>: A button triggering the conversion process.
  • <p id="converted-result"><span>Enter The Number & Hit Convert</span></p>: A paragraph to display the converted result initially with a placeholder message.
  • <p id="error-message"></p>: A paragraph to display error messages.

CSS Styling

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Rubik", sans-serif;
}
body {
  background-color: #1e1c27;
}
.conversion-container {
  background-color: #ffffff;
  width: min(90%, 450px);
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  padding: 3em 2em;
  border-radius: 0.8em;
}
.input-section {
  display: grid;
  grid-template-columns: 9fr 3fr;
  gap: 1em;
}
.input-field {
  padding: 1em 0.5em;
  color: #262e45;
  border: 2px solid #e3e4ef;
}
.input-field:focus {
  border-color: #4470f3;
}
.convert-button {
  border: none;
  background-color: #4470f3;
  color: #ffffff;
}
.input-field,
.convert-button {
  font-size: 1em;
  outline: none;
  border-radius: 0.5em;
}
#error-message {
  background-color: #fc4747;
  text-align: center;
  color: #ffffff;
  margin-top: 0.5em;
}
#converted-result {
  font-size: 1.2em;
  text-align: center;
  font-weight: 600;
  color: #262e45;
  margin-top: 2em;
}
#converted-result span {
  font-size: 0.9em;
}
CSS

Explanation:

  • .conversion-container: Styles the main container for the conversion functionality.
  • .input-section: Styles the grid layout for the input field and the convert button.
  • .input-field: Styles the input field for entering numbers.
  • .input-field:focus: Styles the input field when it is in focus.
  • .convert-button: Styles the convert button.
  • #error-message: Styles the container for error messages.
  • #converted-result: Styles the container for the converted result.
  • #converted-result span: Styles the span within the converted result paragraph.

JavaScript Functionality

let inputNumber = document.getElementById("input-number");
let convertButton = document.getElementById("convert-button");
let errorMessage = document.getElementById("error-message");
let convertedResult = document.getElementById("converted-result");

const romanNumeralMap = {
  M: 1000,
  CM: 900,
  D: 500,
  CD: 400,
  C: 100,
  XC: 90,
  L: 50,
  XL: 40,
  XXX: 30,
  XX: 20,
  X: 10,
  IX: 9,
  V: 5,
  IV: 4,
  I: 1,
};

convertButton.addEventListener("click", () => {
  convertToRoman(inputNumber.value);
  inputNumber.value = "";
});

function convertToRoman(num) {
  let number = parseInt(num);

  if (num.trim().length == 0) {
    errorMessage.innerHTML = "Invalid Input";
    convertedResult.innerHTML = "";
    return false;
  }
  if (number > 4999 || number < 1) {
    errorMessage.innerHTML = "Input Out Of Range";
    convertedResult.innerHTML = "";
    return false;
  }
  errorMessage.innerHTML = "";
  convertedResult.innerHTML = "";

  let result = "";
  let romanNumerals = Object.keys(romanNumeralMap);
  romanNumerals.forEach((key) => {
    while (romanNumeralMap[key] <= number) {
      number -= romanNumeralMap[key];
      result += key;
    }
  });
  convertedResult.innerHTML = result;
}
JavaScript

Explanation:

  • const romanNumeralMap: An object that maps Roman numerals to their corresponding values.
  • convertButton.addEventListener("click", () => {...}): Event listener for the conversion button.
  • function convertToRoman(num) {...}: The main function to convert a given number to Roman numerals.

Conversion Logic Explanation:

  • parseInt(num): Converts the input to an integer for processing.
  • Error Handling: Checks for invalid input or numbers out of the supported range and displays appropriate error messages.
  • Roman Numeral Conversion: Utilizes a loop to iterate through the Roman numerals, subtracting their values from the input number and appending the corresponding Roman numeral to the result string.

Conclusion

This Roman Numeral Converter provides a user-friendly interface to convert modern numbers into Roman numerals. Feel free to integrate this code into your projects, and don’t hesitate to customize the styles or extend the functionality to meet your specific needs.

Happy coding!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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