Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
trying to convert decimal numbers to roman numbers with for in javascript

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);

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!