Created
January 28, 2014 17:41
-
-
Save EpiphanyMachine/8672409 to your computer and use it in GitHub Desktop.
This file contains hidden or 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(number) { | |
'use strict'; | |
var v = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1], // set values | |
r = [ 'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'], // set numerals | |
n = Math.round(number), // clean number, round to nearest integer | |
limit = 3999, // set max limit to check integers against | |
s = '', // create empty string for numerals | |
val; // create temp val variable | |
// check if number is greater than the limit | |
if (n > limit || n < 1) { return ''; } | |
// with M as 1000 the greatest number of options is 13 | |
for (var i = 0; i <= 12; i++) { | |
// in order of highest values | |
val = v[i]; | |
// while the number is greater than the value being compared | |
while (n >= val) { | |
// subtract the value being compared | |
n -= val; | |
// add the corrosponding roman numeral to the resultant string | |
s += r[i]; | |
} | |
// when the value is decremented to 0 return the resulting roman numeral | |
if (n === 0) { return s; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another Solution from Created by Matthew, Daniel, Corey and Ray. https://gist.github.com/rayshan/8670186