Roman Numeral Converter

JavaScript
function convertToRoman(num) {

    var roman = [];
    var numString = num.toString();
    //split number into an array containing only any digits entered
    var numArr = numString.match(/\d/g);
    //store value of the number without any special characters, such as commas
    var bareNumber = numArr.join('');
    var thousands = bareNumber / 1000;
    //initialize variables for each index in the array that contains the last 3 digits
    var hundreds = 0;
    var tens = 1;
    var ones = 2;

    //if the number has digits for the thousands, push an "M" into the array for each thousand
    if (thousands >= 1) {
        thousands = Math.floor(thousands);
        console.log(thousands);

        for (i = 0; i < thousands; i++) {
            roman.push("M");
        }
        var thousandsString = thousands.toString();

        //remove each digit for thousands from the beginning of the array
        for (i = 0; i < thousandsString.length; i++) {
            numArr.shift();
        }
    }

    //function to convert last 3 array digits to their Roman numerals
    function parseNumbers(first, second, third, position) {
        //hundreds, tens, or ones: 1-2
        if (numArr[position] >= 1 && numArr[position] <= 3) {
            for (i = 0; i < numArr[position]; i++) {
                roman.push(first);
            }
        }
        //4
        if (numArr[position] == 4) {
            roman.push(first + second);
        }
        //5
        if (numArr[position] == 5) {
            roman.push(second);
        }
        //6-8
        if (numArr[position] >= 6 && numArr[position] <= 8) {
            roman.push(second);
            for (i = 5; i < numArr[position]; i++) {
                roman.push(first);
            }
        }
        //9
        if (numArr[position] == 9) {
            roman.push(first + third);
        }
    }

    //if there is a hundreds digit, do the conversion for this digit
    console.log(numArr.length);
    if (numArr.length === 3) {
        //hundreds
        parseNumbers("C", "D", "M", hundreds);
    }

    //if there is a tens digit, do the conversion for this digit
    if (numArr.length >= 2) {

        if (numArr.length === 2) {
            //if the number starts with tens, shift the array position fed to the parser to the correct digit
            tens = 0;
            ones = 1;
        }
        //tens
        parseNumbers("X", "L", "C", tens);
    }

    //if there is a ones digit, do the conversion for this digit
    if (numArr.length >= 1) {
        //if the number starts with ones, shift the array position fed to the parser to the correct digit
        if (numArr.length === 1) {
            ones = 0;
        }
        //ones
        parseNumbers("I", "V", "X", ones);
    }

    num = roman.toString();
    num = num.replace(/,/g, '');
    console.log(num);
    return num;
}

Leave a Reply