Skip to content

Instantly share code, notes, and snippets.

@MarcSymonds
Created April 25, 2017 08:42
Show Gist options
  • Save MarcSymonds/c5e09acaf41049b042a23fc3f096f8b0 to your computer and use it in GitHub Desktop.
Save MarcSymonds/c5e09acaf41049b042a23fc3f096f8b0 to your computer and use it in GitHub Desktop.
JavaScript.Example - Convert a number to Roman numerals. Only works effectively up to 9999.
function convertToRoman(num) {
var romanNumerals = [
{number: 1, numeral: "I", sub: 0},
{number: 5, numeral: "V", sub: -1},
{number: 10, numeral: "X", sub: -2},
{number: 50, numeral: "L", sub: -1},
{number: 100, numeral: "C", sub: -2},
{number: 500, numeral: "D", sub: -1},
{number: 1000, numeral: "M", sub: -2}
];
var rni = romanNumerals.length - 1;
var result = "";
var rn, rnx;
while (num > 0 && rni >= 0) {
rn = romanNumerals[rni];
while (num >= rn.number) {
result += rn.numeral;
num -= rn.number;
}
// Symbols are placed from left to right in order of value, starting
// with the largest. However, in a few specific cases, to avoid four
// characters being repeated in succession (such as IIII or XXXX),
// subtractive notation is used where two symbols are used which
// indicate a smaller number being subtracted from a larger number;
// for example, 900 is represented as CM, which means 100 subtracted
// from 1000.
if (rn.sub !== 0) {
rnj = rni + rn.sub;
rnx = romanNumerals[rnj];
if (num >= (rn.number - rnx.number)) {
result = result + rnx.numeral + rn.numeral;
num -= (rn.number - rnx.number);
}
}
--rni;
}
return result;
}
// A longer, but more direct approach.
function convertToRoman(num) {
var result = "";
while (num >= 1000) {
result += "M";
num -= 1000;
}
if (num >= 900) {
result += "CM";
num -= 900;
}
if (num >= 500) {
result += "D";
num -= 500;
}
if (num >= 400) {
result += "DC";
num -= 400;
}
while (num >= 100) {
result += "C";
num -= 100;
}
if (num >= 90) {
result += "XC";
num -= 90;
}
if (num >= 50) {
result += "L";
num -= 50;
}
if (num >= 40) {
result += "XL";
num -= 40;
}
while (num > 10) {
result += "X";
num -= 10;
}
if (num == 9) {
result += "IX";
num -= 9;
}
if (num >= 5) {
result += "V";
num -= 5;
}
if (num == 4) {
result += "IV";
num -= 4;
}
while (num > 0) {
result += "I";
num--;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment