Skip to content

Instantly share code, notes, and snippets.

@ramyareye
Created July 25, 2022 04:15
Show Gist options
  • Save ramyareye/7f294401f9ddd9abb7ccea55a4c7ab1d to your computer and use it in GitHub Desktop.
Save ramyareye/7f294401f9ddd9abb7ccea55a4c7ab1d to your computer and use it in GitHub Desktop.
number to roman
var 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
};
function convertToRoman(num) {
if (isNaN(num)) return NaN;
var str = '';
for (var i in roman) {
var repeat = Math.floor(num / roman[i]);
num -= repeat * roman[i];
str += i.repeat(repeat);
}
return str;
}
console.log(convertToRoman(3));
console.log(convertToRoman(4));
console.log(convertToRoman(9));
console.log(convertToRoman(58));
console.log(convertToRoman(1994));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment