Skip to content

Instantly share code, notes, and snippets.

@EpiphanyMachine
Created January 28, 2014 17:41
Show Gist options
  • Save EpiphanyMachine/8672409 to your computer and use it in GitHub Desktop.
Save EpiphanyMachine/8672409 to your computer and use it in GitHub Desktop.
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; }
}
}
@EpiphanyMachine
Copy link
Author

Another Solution from Created by Matthew, Daniel, Corey and Ray. https://gist.github.com/rayshan/8670186

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment