Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a number into a Roman Numeral in javaScript

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

like image 439
DD77 Avatar asked Jan 31 '12 16:01

DD77


People also ask

How do you convert Roman numerals to numbers in Javascript?

Algorithm to convert Roman Numerals to Integer Number: Take symbol one by one from starting from index 0: If current value of symbol is greater than or equal to the value of next symbol, then add this value to the running total. else subtract this value by adding the value of next symbol to the running total.


2 Answers

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; } 
like image 68
Rene Pot Avatar answered Sep 30 '22 10:09

Rene Pot


function romanize(num) {   var lookup = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1},roman = '',i;   for ( i in lookup ) {     while ( num >= lookup[i] ) {       roman += i;       num -= lookup[i];     }   }   return roman; } 

Reposted from a 2008 comment located at: http://blog.stevenlevithan.com/archives/javascript-roman-numeral-converter

VIEW DEMO

like image 41
jaggedsoft Avatar answered Sep 30 '22 10:09

jaggedsoft