Build a Roman Numeral Converter

In the for loop, Roman Numerals are repeating more than 4 times. I created an if statement to fix it but can’t seem to get through. Here is my code.

const input = document.getElementById('number');
const convertBtn = document.getElementById('convert-btn');
const output = document.getElementById('output');

const arabicToRoman = () => {
  let romanNum = "";
  const romanArabic = {
    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
  };
//Editable region

  for (let key in romanArabic) {
    const value = romanArabic[key];
    let number = parseInt(input.value);

    while (number >= value) {
      number -= value;
      romanNum += key;
      if(key++ >3){break}
      
    }
  }

  output.textContent = romanNum;
};

const convert = () => {
  if (input.value === "") {
    output.textContent = "Please enter a valid number";
  } else if (parseInt(input.value) === -1) {
    output.textContent = "Please enter a number greater than or equal to 1";
  } else if (parseInt(input.value) >= 3999) {
    output.textContent = "Please enter a number less than or equal to 3999";
  } else {
    arabicToRoman(parseInt(input.value));
  }
};

convertBtn.addEventListener("click", convert); 

Hi @Coder_2024_Eng

image

Looks like you have a loop within a loop. Which maybe why the extra roman numerals and NaN are appearing in the result.

Happy coding

@Teller
I was trying to figure out the condition that breaks it after identifying three similar characters within the updated romanNum variable.Should I loop over the romanNum or any approach further can be appreciated
NB:I have omitted the if statement in the code.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.