Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Program to Convert a String to Roman Numerals
Next article icon

JavaScript Program to Convert a String to Roman Numerals

Last Updated : 16 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to convert a string to Roman numerals using JavaScript. Converting a string to Roman numerals in JavaScript is a common task when working with text data containing numeric values in Roman numeral format. Roman numerals are a numeral system used in ancient Rome, and they are still used in various contexts such as numbering book chapters, naming monarchs, or denoting particular years.

These are the following methods to convert a string to Roman numerals using JavaScript:

  • Using an Array of Values and Symbols
  • Using an object
  • Using a Map

Using an Array of Values and Symbols

  • In this approach, we are creating two arrays having values in an integer and in a string as a Roman count and one variable for storing the Roman numeral representation.
  • Iterate and check if the current num is greater than or equal to values[i] If true, add symbols[i] to the result and subtract values[i] from num. Repeat until num is no longer greater than or equal to values[i].
  • Return the result as the Roman numeral representation of the input number.

Example: This example shows the implementation of the above-explained approach.

JavaScript
function stringToRoman(num) {     const values =          [1000, 900, 500, 400, 100,           90, 50, 40, 10, 9, 5, 4, 1];     const symbols =          ['M', 'CM', 'D', 'CD', 'C',           'XC', 'L', 'XL', 'X', 'IX',           'V', 'IV', 'I'];     let result = '';      for (let i = 0; i < values.length; i++) {         while (num >= values[i]) {             result += symbols[i];             num -= values[i];         }     }      return result; }  const input = "2013"; const result = stringToRoman(parseInt(input)); console.log(result); 

Output
MMXIII 

Using an object

  • Create an object that maps Roman numeral symbols to their decimal values and an empty string to store the Roman numeral representation.
  • Iterate through the Roman numeral symbols in descending order of their decimal values. For each symbol, calculate how many times it fits into the input number and append that symbol to the result string that many times.
  • Subtract the portion of the number converted to Roman numerals from the input. Repeat this process for all symbols. And then return the result string.

Example: This example shows the implementation of the above-explained approach.

JavaScript
function stringToRoman(num) {     let roman = {         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 str = '';      for (let i of Object.keys(roman)) {         let q = Math.floor(num / roman[i]);         num -= q * roman[i];         str += i.repeat(q);     }      return str; }  console.log(stringToRoman(1234)); 

Output
MCCXXXIV 

Using Recursion

Using recursion, find the largest Roman numeral less than or equal to the number and append it to the result. Recurse with the remaining value until it reaches zero. Return the concatenated Roman numerals.

Example:

JavaScript
function toRoman(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' }     ];      if (num === 0) return '';      for (let i = 0; i < romanNumerals.length; i++) {         if (num >= romanNumerals[i].value) {             return romanNumerals[i].numeral + toRoman(num - romanNumerals[i].value);         }     } }   console.log(toRoman(354)); // Output: "CCCLIV" 

Output
CCCLIV 

Using a Map

In this approach, we utilize a Map object to store the Roman numeral symbols along with their corresponding integer values. This allows for efficient lookups and a clean implementation.

Example: This example shows the implementation of the above approach.

JavaScript
function stringToRoman(num) {     const romanMap = new Map([         ['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 result = '';      for (let [symbol, value] of romanMap) {         while (num >= value) {             result += symbol;             num -= value;         }     }      return result; }  console.log(stringToRoman(1987)); // Output: "MCMLXXXVII" 

Output
MCMLXXXVII 

Next Article
JavaScript Program to Convert a String to Roman Numerals

A

anjugaeu01
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Program
  • Geeks Premier League 2023

Similar Reads

    Javascript Program to Convert Integer to Roman Numerals
    Given an Integer number, the task is to convert the Integer to a Roman Number in JavaScript. Roman numerals are a numeral system that originated in ancient Rome and remained the usual way of writing numbers throughout Europe well into the Late Middle Ages. Table of Content Using a Lookup ObjectUsing
    2 min read
    Java Program to Convert Long to String
    The long to String conversion in Java generally comes in need when we have to display a long number in a GUI application because everything is displayed in string form. In this article, we will learn about Java Programs to convert long to String. Given a Long number, the task is to convert it into a
    4 min read
    PHP Program to Convert Integer to Roman Number
    Converting an integer to a Roman number is a common problem often encountered in applications dealing with dates, historical data, and numeral representations. In this article, we will explore various approaches to converting an integer to Roman numerals in PHP. Table of Content Using Simple Mapping
    2 min read
    Javascript Program For Converting Roman Numerals To Decimal Lying Between 1 to 3999
    Given a Romal numeral, the task is to find its corresponding decimal value.Example : Input: IXOutput: 9IX is a Roman symbol which represents 9 Input: XLOutput: 40XL is a Roman symbol which represents 40Input: MCMIVOutput: 1904M is a thousand, CM is nine hundred and IV is fourRoman numerals are based
    3 min read
    Java Program to Convert Octal to Binary
    Given an Octal number as input, the task is to convert that number into its Binary equivalent number. Example: Input: Octal Number = 513 Output: Binary equivalent value is: 101001011 Explanation : Binary equivalent value of 5: 101 Binary equivalent value of 1: 001 Binary equivalent value of 3: 011Oc
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences