Skip to content

Instantly share code, notes, and snippets.

@jSayal
Created December 6, 2015 08:47
Show Gist options
  • Select an option

  • Save jSayal/49420e16c34c64d6031d to your computer and use it in GitHub Desktop.

Select an option

Save jSayal/49420e16c34c64d6031d to your computer and use it in GitHub Desktop.
convert numbers to roman numerals
function findRomanNumeral(number) {
var romanNumbers = {
1 : "I",
2 : "II",
3 : "III",
4 : "IV",
5 : "V",
6 : "VI",
7 : "VII",
8 : "VIII",
9 : "IX",
10 : "X",
20 : "XX",
30 : "XXX",
40 : "XL",
50 : "L",
60 : "LX",
70 : "LXX",
80 : "LXXX",
90 : "XC",
100 : "C",
200 : "CC",
300 : "CCC",
400 : "CD",
500 : "D",
600 : "DC",
700 : "DCC",
800 : "DCCC",
900 : "CM",
1000 : "M"
};
// find digit places - ones, tens, hundreds, thousands etc...
// last element in digitPlaces array is ones, second last is
// tens, and so on
// ********************************************************
var digitPlaces = [];
var divisor = Math.pow(10, Math.floor(Math.log(number)/Math.log(10)));
digitPlaces.push(Math.floor(number / divisor));
while (divisor > 1) {
digitPlaces.push(Math.floor((number % divisor)/(divisor / 10)));
divisor /= 10;
}
// convert digit places array to roman numeral
// *********************************************
var result = "";
// thousands
if (number >= 1000) {
var thousands = 0, tmpThousands = "";
for (var i = 0; i < digitPlaces.length - 3; i++) {
tmpThousands += digitPlaces[i];
}
thousands = parseInt(tmpThousands);
for (var i=0; i<thousands; i++) {
result += romanNumbers[1000];
}
}
// hundreds
if (number >= 100) {
var hundreds = digitPlaces[digitPlaces.length - 3];
if(hundreds > 0)
result += romanNumbers[hundreds * 100];
}
// tens
if (number >= 10) {
var tens = digitPlaces[digitPlaces.length - 2];
if(tens > 0)
result += romanNumbers[tens * 10];
}
// ones
if (number >= 1) {
var ones = digitPlaces[digitPlaces.length - 1];
if(ones > 0)
result += romanNumbers[ones];
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment