0

I don't know if I can ask or not but the answers that appear here don't help me. I'm trying to convert decimal numbers to roman numbers in javascript. I'm dividing the numbers in digits and seeing the different cases. Until now, I'm in 2 digits case. The problem is that when I try to read the "decenas" (tens) part, it says that the number I'm looking for doesn't exist in the object, and that's not correct. Can you help me figure out why? When I pass 12, it only returns the unit part.

    function convertToRoman(num) {
     let nums = num.toString();
     let roman = ''; //here I'll keep the results
     let numbers = {
       '1': 'I',
       '2': 'II',
       '3': 'III',
       '4': 'IV',
       '5': 'V',
       '6': 'VI',
       '7': 'VII',
       '8': 'VIII',
       '9': 'IX',
       '10': 'X'
     };
     let unidad = nums[1]; //here I keep the units part
     let decena =nums[0]*10; //here the tens part
     console.log("nums Length:",nums.length);
     //If the number has 1 digit:
     if (nums.length === 1){
      for (let n in numbers){
        if (n === nums){
          roman = numbers[n];
        }
      }
     }
     //If the number has 2 digits:
     if (nums.length === 2){
       for ( let n in numbers){
         if(n === decena){
           roman += numbers[n];
         }
       }
       for ( let n in numbers){
         if(n === unidad){
          roman += numbers[n];
         }
       }
     }
    
    
    console.log("decena:", decena, "unidad:", unidad, "En romano:", roman);
     
     return roman
    }
    
    convertToRoman(12);
D B
  • 3
  • 4
  • This might help you https://stackoverflow.com/a/32851198/16758137 – Art Feb 23 '22 at 12:38
  • `if(n === decena)` - `n` is a string value, `decena` is a number value. They will never be identical. Either use a less strict comparison, or use a data structure with numbers instead of strings, or convert your number to a string. – David Feb 23 '22 at 12:40

1 Answers1

-1

Use this code for converting -

function convertToRoman(num) 
{
  let map = {
    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"
  }
  let roman = "";
  let romankeys = Object.keys(map).reverse();
  romankeys.forEach((keys) => {
      while(keys <= num)
      {
        roman += map[keys];
        num -= keys;
      }
        
  });
  return roman;
}
console.log(convertToRoman(58));
Archit Gargi
  • 634
  • 1
  • 8
  • 24