JSFiddle - React, Tailwind, and code Playground
by Steven Senkus
JavaScript
function toRoman(int) {
let romanString = '';
let intRemainder = int;
if (Math.floor(intRemainder / 1000) > 0) {
for (let m = 0; m < Math.floor(int / 1000); m++) {
romanString += 'M';
intRemainder -= 1000;
}
}
if (Math.floor(intRemainder / 900) > 0) {
romanString += 'CM';
intRemainder -= 900;
} else if (Math.floor(intRemainder / 500) > 0) {
romanString += 'D';
intRemainder -= 500;
}
if (Math.floor(intRemainder / 100) > 0) {
let numC = Math.floor(intRemainder / 100);
for (let m = 0; m < numC; m++) {
romanString += 'C';
intRemainder -= 100;
}
}
if (Math.floor(intRemainder / 90) > 0) {
romanString += 'XC';
intRemainder -= 90;
} else if (Math.floor(intRemainder / 50) > 0) {
romanString += 'L';
intRemainder -= 50;
}
if (Math.floor(intRemainder / 10) > 0) {
let numX = Math.floor(intRemainder / 10);
for (let m = 0; m < numX; m++) {
romanString += 'X';
intRemainder -= 10;
}
}
if (Math.floor(intRemainder / 9) > 0) {
romanString += 'IX';
intRemainder -= 9;
} else if (Math.floor(intRemainder / 5) > 0) {
romanString += 'V';
intRemainder -= 5;
}
if (Math.floor(intRemainder / 1) > 0) {
let numI = Math.floor(intRemainder / 1);
for (let m = 0; m < numI; m++) {
romanString += 'I';
intRemainder--;
}
}
return romanString;
}
for (let num = 1; num < 100; num++) {
console.log(toRoman(num));
}