CFLib.org – Common Function Library Project

romanToDecimal(input)

Last updated February 4, 2010

author

Raymond Camden

Version: 2 | Requires: CF5 | Library: StrLib

Description:
Converts Roman numerals to decimal. Assumes a valid ROman numeral.

Return Values:
Returns a number.

Example:

<cfset inputs = "XX,XI,IV,VIII,MC,DL,XL">
<cfloop index="input" list="#inputs#">
	<cfoutput>
	#input#=#romantodec(input)#<br/>
	</cfoutput>
</cfloop>

Parameters:

Name Description Required
input Roman number input. Yes

Full UDF Source:

/**
 * Converts Roman numerals to decimal.
 * v2 fix by for non standard things like IIX, fix done by Gary Funk
 * 
 * @param input 	 Roman number input. (Required)
 * @return Returns a number. 
 * @author Raymond Camden (ray@camdenfamily.com) 
 * @version 2, February 4, 2010 
 */
function romantodec(input) {
	var romans = {};
	var result = 0;
	var pos = 1;
	var char = "";
	var thisSum = "";
	var nextchar = "";
	var subSum = 0;
		
	romans["I"] = 1;
	romans["V"] = 5;
	romans["X"] = 10;
	romans["L"] = 50;
	romans["C"] = 100;
	romans["D"] = 500;
	romans["M"] = 1000;

	while(pos lte len(input)) {
		char = mid(input, pos, 1);
		subSum += romans[char];
		if(pos != len(input)) {
			nextchar = mid(input, pos + 1, 1);
			if(romans[char] == romans[nextchar]) {
				pos++;
			} else if(romans[char] < romans[nextchar]) {
				result = result + romans[nextchar] - subSum;
				subSum = 0;
				pos += 2;
			} else {
				result = result + subSum;
				subSum = 0;
				pos++;
			}
		} else {
			result = result + subSum;
			pos++;
		}
	}    
	return result;
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson