Created
February 22, 2017 09:37
-
-
Save pmutua/548d6d7ff0be2df3150a50189c0dfe1b to your computer and use it in GitHub Desktop.
simple code to convert numbers to roman numerals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function toRoman(num) { | |
var decimal = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; | |
var roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]; | |
var result = ''; | |
for (var i = 0; i <= decimal.length; i++) {//look up the array decimal for values | |
//looping over every element of arrays | |
while (num % decimal[i] < num) { | |
//keep trying the same number until we need to move to a smaller one | |
result =result+ roman[i]; | |
//add the matching roman number to our result | |
num =num-decimal[i]; | |
//subtract decimal value of the roman number from our number | |
}//end while loop | |
}//end for loop | |
return result; | |
} //end function statement | |
//call function example | |
toRoman(11) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment