Convert a number into a Roman Numeral in javaScript

DD77 picture DD77 · Jan 31, 2012 · Viewed 118.9k times · Source

How can I convert integers into roman numerals?

function romanNumeralGenerator (int) {

}

For example, see the following sample inputs and outputs:

1 = "I"
5 = "V"
10 = "X"
20 = "XX"
3999 = "MMMCMXCIX"

Caveat: Only support numbers between 1 and 3999

Answer

Rene Pot picture Rene Pot · Jan 31, 2012

There is a nice one here on this blog I found using google:

http://blog.stevenlevithan.com/archives/javascript-roman-numeral-converter

function romanize (num) {
    if (isNaN(num))
        return NaN;
    var digits = String(+num).split(""),
        key = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
               "","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
               "","I","II","III","IV","V","VI","VII","VIII","IX"],
        roman = "",
        i = 3;
    while (i--)
        roman = (key[+digits.pop() + (i * 10)] || "") + roman;
    return Array(+digits.join("") + 1).join("M") + roman;
}