w3resource

JavaScript: Convert an integer into a Roman Numeral

JavaScript Math: Exercise-21 with Solution

Write a JavaScript function that converts an integer into a Roman numeral.

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Write a JavaScript function that Convert an integer into a Roman Numeral</title>
</head>
<body>

</body>
</html>

Pictorial Presentation:

JavaScript: Math - Convert an integer into a Roman Numeral.

JavaScript Code:

function integer_to_roman(num) {
if (typeof num !== 'number') 
return false; 

var digits = String(+num).split(""),
key = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
"","I","II","III","IV","V","VI","VII","VIII","IX"],
roman_num = "",
i = 3;
while (i--)
roman_num = (key[+digits.pop() + (i * 10)] || "") + roman_num;
return Array(+digits.join("") + 1).join("M") + roman_num;
}

console.log(integer_to_roman(27));

Sample Output:

XXVII

Flowchart:

Flowchart: JavaScript Math- Convert an integer into a Roman Numeral

Live Demo:

See the Pen javascript-math-exercise-21 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to evaluate binomial coefficients.
Next: Write a JavaScript function that Convert Roman Numeral to Integer.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.