Translating from Roman to Decimal Numbers
Feb 4 2010
Ray posted an entry on his blog dealing with converting Roman Numbers to decimal numbers. I ran his code and pointed out that IIX returned 10 instead of 8.
A debate ensued on whether IIX is valid. Ray replied:
Now I'm going to ask you to put up or shut up! ;) If you can find me proof that IIX (or IIC, etc) is valid, I'll support it. ;)
It is still undecided if IIX is valid. I felt it should return the correct value or no value at all. But then I thought, if the number was ever used, the converter should convert it. So I took Ray's code, made some changes and now it should convert any Roman Numeral you throw at it.
EDIT: I found a serious flaw in the logic. Here is the correct code, even though the other did work in most cases. The first code failed on MCCCIIIX. It returned 2107 instead of 1307.
2/**
3 * Converts Roman numerals to decimal.
4 *
5 * @param input Roman number input. (Required)
6 * @return Returns a number.
7 * @author Raymond Camden (ray@camdenfamily.com)
8 * @version 1, February 2, 2010
9 */
10function romantodec(input) {
11 var romans = {};
12 var result = 0;
13 var pos = 1;
14 var char = "";
15 var thisSum = "";
16 var subSum = 0;
17 var nextchar = "";
18
19 romans["I"] = 1;
20 romans["V"] = 5;
21 romans["X"] = 10;
22 romans["L"] = 50;
23 romans["C"] = 100;
24 romans["D"] = 500;
25 romans["M"] = 1000;
26
27 while(pos lte len(input)) {
28 char = mid(input, pos, 1);
29 subSum += romans[char];
30 if(pos != len(input)) {
31 nextchar = mid(input, pos + 1, 1);
32 if(romans[char] == romans[nextchar]) {
33 pos++;
34 } else if(romans[char] < romans[nextchar]) {
35 result = result + romans[nextchar] - subSum;
36 subSum = 0;
37 pos += 2;
38 } else {
39 result = result + subSum;
40 subSum = 0;
41 pos++;
42 }
43 } else {
44 result = result + subSum;
45 pos++;
46 }
47 }
48 return result;
49}
50</cfscript>
I am pretty sure there is a better way yo do this, so please feel free to leave suggestions and ideas.









