How to use an Array of Values and Symbols In Javascript
- 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.
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
JavaScript Program to Convert a String to Roman Numerals
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